Home > OS >  Don't wait control and process execution sequence
Don't wait control and process execution sequence

Time:11-08

I am read a book, there is a topic:
Write another program using The fork () The child process should print "hello". The parent process should print "goodbye". You should try to ensure that the child process always prints first. Can you do this without calling wait () in the parent?

I wrote a program to find and can't realize the topic request, trouble to help see

 
#include
#include
#include
#include
#include
#include

Int main (void)
{
Int pipeFd1 [2].
Int pipeFd2 [2].
If (1==pipe (pipeFd1))
{
Perror (" pipe fail ");
The exit (EXIT_FAILURE);
}
If (1==pipe (pipeFd2))
{
Perror (" pipe fail ");
The exit (EXIT_FAILURE);
}


Pid_t pid=fork ();
If (pid & lt; 0)
{
Perror (" fork fail ");
The exit (EXIT_FAILURE);
}
Else if (0==pid)
{
Int loops=10;
Close (pipeFd1 [1]);
Close (pipeFd2 [0]);
While (loops -)
{
Char buf [2].
Printf (" Hello ");
//fflush (stdout);
Write (pipeFd2 [1], "OK", 2);
Read (pipeFd1 [0], buf, 2);
If (STRNCMP (buf, "OK", 2))
{
Fprintf (stderr, "pipe data error \ n");
The kill (getppid (), SIGKILL);
The exit (EXIT_FAILURE);
}
}
}
The else
{
Int loops=10;
Close (pipeFd1 [0]);
Close (pipeFd2 [1]);
While (loops -)
{
Char buf [2].
Read (pipeFd2 [0], buf, 2);
If (STRNCMP (buf, "OK", 2))
{
Fprintf (stderr, "pipe data error \ n");
The kill (pid, SIGKILL);
The exit (EXIT_FAILURE);
}
Printf (" Goodbye \ n ");
//fflush (stdout);
Write (pipeFd1 [1], "OK", 2);
}
}
return 0;
}

CodePudding user response:

Can also use a semaphore

CodePudding user response:

Can see inter-process communication,,

CodePudding user response:

An introduction to your book should be a "operating system"
  • Related