저는 파이프, 분기를 만드는 프로그램을 작성하고 있습니다. 부모는 한 번에 하나의 자식에 명령 줄 인수를 보냅니다. 아이는 그들을 셀 것으로 가정하고, 그 다음에 부모는 아이를 낳아서 얼마나 많은 주장이 있는지를 출력합니다. 여기에 내가 지금까지 가지고있는 것입니다 :부모가 자식에게 명령 줄 인수를 보냅니다.
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
int main(int argc, char **argv)
{
pid_t pid;
int status;
int comm[2];
char buffer[BUFSIZ];
// set up pipe
if (pipe(comm)) {
printf("pipe error\n");
return -1;
}
// call fork()
pid = fork();
// fork failed
if (pid < 0) {
printf("fork error %d\n", pid);
return -1;
}
else if (pid == 0) {
// -- running in child process --
int nChars = 0;
close(comm[1]);
// Receive characters from parent process via pipe
// one at a time, and count them.
while(read(comm[0], buffer, sizeof(buffer)) != '\n')
nChars++;
// Return number of characters counted to parent process.
return nChars;
}
else {
// -- running in parent process --
int nChars = 0;
close(comm[0]);
// Send characters from command line arguments starting with
// argv[1] one at a time through pipe to child process.
char endl='\n';
for (int a = 1; a < argc; a++) {
for (int c = 0; c < strlen(argv[a]); c++) {
write(comm[1], &argv[a][c], 1);
}
}
write(comm[1], &endl, 1);
// Wait for child process to return. Reap child process.
// Receive number of characters counted via the value
// returned when the child process is reaped.
waitpid(pid, &status, 0);
printf("child counted %d chars\n", nChars);
return 0;
}
}
끝없이 실행되는 것 같습니다. 루프 중 하나에 걸려 있어야합니다. 무슨 일 이니?
도움말 Windows에서 * 방법 * 너무 많은 시간을 소비하고 최근 리눅스에 반환 된 남자. 'fork()'이후의 자식 프로세스에서 부모 프로세스의 argc와 argv []가 상속되지 않는다 (복사, 어쨌든)? (아직 코드를 해부하지 않았으므로 잠시만 기다려주십시오. 사실이라면 코드를 다소 쓸모 없게 만듭니다). – WhozCraig
예 자식 프로세스가 "어떤 방법 으로든"main에 대한 인수를 사용하지 않아야한다고 말하는 것을 잊어 버렸습니다. 이것은 숙제 Btw입니다. – chillpenguin