C 控制父、子进程的先后顺序执行
#include "include/apue.h"
static int pfd1[2], pfd2[2];
void ?TELL_WAIT(void)
{
?? ?//創建管道
?? ?if (pipe(pfd1) < 0 || pipe(pfd2) < 0)
?? ??? ?err_sys("pipe error");
}
void TELL_PARENT(pid_t ?pid)
{
?? ?//把數據寫進pfd2管道(寫端-標準輸出)
?? ?if (write(pfd2[1], "c", 1) != 1)
?? ??? ?err_sys("write ?error");
}
void WAIT_PARENT(void)
{
?? ?char c;
?? ?//從pfd1管道(讀端-標準輸入)中讀數據
?? ?if (read(pfd1[0], &c, 1) != 1)
?? ??? ?err_sys("read error");
? ? ? ? ??
?? ?if (c != 'p')
?? ??? ?err_quit("WAIT_PARENT:incorrect data");
}
void ?TELL_CHILD(pid_t ?pid)
{
?? ?if (write(pfd1[1], "p", 1) != 1)
?? ??? ?err_sys("write error");
}
void WAIT_CHILD(void)
{ ?
?? ?char c;
?? ?if (read(pfd2[0], &c, 1) != 1)
?? ??? ?err_sys("read error");
?? ?if ( c != 'c' )
?? ??? ?err_quit("WAIT_CHILD: incorrent data");
}
?? ?
int main()
{
?? ?pid_t pid;
?? ?TELL_WAIT();
?? ?if ((pid = fork()) < 0)
?? ?{
?? ??? ?err_sys("fork error!");
?? ?}
?? ?else if (pid == 0)
?? ?{
?? ??? ?TELL_PARENT(getpid());
?? ??? ?WAIT_PARENT();
?? ??? ?printf ("2222222222\n");
?? ?}
?? ?else
?? ?{
?? ??? ?TELL_CHILD(pid);
?? ??? ?WAIT_CHILD();
?? ??? ?printf ("1111111111\n");
?? ?}
?? ??? ?
?? ?return 0;
}
執行結果:
2222222222
11111111111?
總結
以上是生活随笔為你收集整理的C 控制父、子进程的先后顺序执行的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 排序算法:直接插入排序算法实现及分析
- 下一篇: 9. OD-PEID的入门及BASIC(