关于Linux C的问题,为什么会得出这样的结果
- C/C++ code
#include<stdio.h>#include<unistd.h>#include<stdlib.h>int main(){ pid_t pid; int pipefd[2]; char readbuf[2]; if (pipe(pipefd) != 0) { printf("pipe error"); exit(1); } pid = fork(); write(pipefd[1], "1", 2); while(1) { if (pid == 0) { readbuf[0] = '\0'; read(pipefd[0], readbuf, 2); if (strcmp(readbuf, "2") != 0) { write(pipefd[1], readbuf, 2); } else { printf("child:%s\n", readbuf); fflush(stdout); write(pipefd[1], "1", 2); } } else if (pid > 0) { readbuf[0] = '\0'; read(pipefd[0], readbuf, 2); if (strcmp(readbuf, "1") != 0) { write(pipefd[1], readbuf, 2); } else { printf("father:%s\n", readbuf); fflush(stdout); write(pipefd[1], "2", 2); } } else if (pid < 0) { printf("fork error!"); exit(2); } } close(pipefd[0]); close(pipefd[1]); return 0;}
题目的要求是用管道实现父子进程顺序输出1212...,而且只能用管道,不能再使用信号量之类的。
于是我想了一个效率很低的办法
大致的意思就是
父子进程都先读管道,如果管道里面放的是"1"的话则父进程输出并将“2”写入管道,否则把读出的数再次写入。子进程也以类似的形式。
但是输出的结果跟我想的完全不一样,我一直想不通是为什么
求高手指点
[解决办法]
[解决办法]
pid = fork();
write(pipefd[1], "1", 2);
这个代码父子进程都写,因为小于PIPE_SIZE,所以属于原子读写。 现在pipe里有4个字节,'1',0,'1',0.
正确同步代码如下:
- C/C++ code
#include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h>int main(int argc, char* const argv[]) { int notify_child[2]; int notify_parent[2]; if (pipe(notify_child) == -1 || pipe(notify_parent) == -1) { return 1; } pid_t pid = fork(); if (pid == -1) { return 2; } else if (pid > 0) { close(notify_child[0]); close(notify_parent[1]); int loop = 10; char ch; int i; for (i = 0; i != loop; ++ i) { printf("1\n"); write(notify_child[1], "", 1); read(notify_parent[0], &ch, 1); } close(notify_child[1]); close(notify_parent[0]); } else { close(notify_child[1]); close(notify_parent[0]); char ch; while (1) { int ret = read(notify_child[0], &ch, 1); if (ret == 0) { close(notify_child[0]); close(notify_parent[1]); exit(0); } printf("2\n"); write(notify_parent[1], "", 1); } } wait(NULL); return 0;}
[解决办法]
你这个进程间同步出现了问题啊。
父子进程同时运行,父进程在读管道时,子进程可以向管道中写入。
如:
开始时,管道中内容为1。那么子进程执行读取,发现不是2,写入一个1。父进程执行读取,是1并打印,继续还是1...