2
我的代碼對我的課程有問題我必須在不同的過程中運行不同的功能,然後將結果傳回父級並顯示出來。我遇到了問題,所以我目前正在嘗試通過在基本程序中執行來理解,但我仍然遇到錯誤。c多個叉子和管子
首先,我不能得到pid = wait(&status);
它一直說pid是未定義的,那麼當我開始轉移到管道系統,但信息似乎並未達到父項。
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#define PROCS 5
int main(void){
int pipes[PROCS][2];
pid_t ret[PROCS];
int status = 0;
int i;
char msg[PROCS][100];
for(i = 0;i < PROCS; i++){
//create pipes
//create pipes
if (pipe(pipes[i]) != 0) { // Create a new pipe.
printf("Could not create new pipe %d", i);
exit(1);
}
if ((ret[i] = fork()) == -1) {
printf("Could not fork() new process %d\n", i);
exit(1);
}else if (ret[i] == 0) {//if child
close(pipes[i][1]);
char string[] = "child process"; //%d - process id = %d\n", i, getpid();
write(pipes[i][0], string, 25);
exit(0);
}
}
if(getpid() > 0){
for(i = 0; i < PROCS; i++) {
wait(&status);
}
for(i = 0; i < PROCS; i++) {
close(pipes[i][1]);
read(pipes[i][0], &msg[i], 100);
close(pipes[i][0]);
}
printf("test 1 : %s\n", msg[0]);
printf("test 2 : %s\n", msg[1]);
printf("test 3 : %s\n", msg[2]);
printf("parent process - process id = %d\n", getpid());
exit(0);
}
}
thx完美工作,thx指出getpid錯誤,我沒有意識到, –
優秀。按複選標記以接受答案。 – Duck