不用wait控制父子进程执行顺序

myclass242 2017-09-21 09:36:58
我在看一本书,有这么一个题目:
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;
}
...全文
670 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
RedWolf1999 2021-04-06
  • 打赏
  • 举报
回复
/proc/sys/kernel/sched_child_runs_first 改为 1
辣椒油li 2021-04-04
  • 打赏
  • 举报
回复
强制父进程休眠1s可以吗?
Ingsuifon 2020-09-02
  • 打赏
  • 举报
回复
你这本书应该是《操作系统导论》
Allensb 2017-09-29
  • 打赏
  • 举报
回复
可以看看进程间通信。。
zhxianbin 2017-09-22
  • 打赏
  • 举报
回复
也可以用 信号量

23,120

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧