我在看一本書,有這么一個題目:
Write another program using 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?
我寫了一個程式發現并不能實作題目要求,麻煩幫忙看看
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
int main(void)
{
int pipeFd1[2];
int pipeFd2[2];
if(-1 == pipe(pipeFd1))
{
perror("pipe fail");
exit(EXIT_FAILURE);
}
if(-1 == pipe(pipeFd2))
{
perror("pipe fail");
exit(EXIT_FAILURE);
}
pid_t pid = fork();
if(pid < 0)
{
perror("fork fail");
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");
kill(getppid(), SIGKILL);
exit(EXIT_FAILURE);
}
}
}
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");
kill(pid, SIGKILL);
exit(EXIT_FAILURE);
}
printf("Goodbye\n");
//fflush(stdout);
write(pipeFd1[1], "OK", 2);
}
}
return 0;
}
uj5u.com熱心網友回復:
也可以用 信號量uj5u.com熱心網友回復:
可以看看行程間通信。。uj5u.com熱心網友回復:
你這本書應該是《作業系統導論》轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/9766.html
標籤:應用程序開發區
