关于Linux C的问题,为什么会得出这样的结果
#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;}
#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...