pipes
의 사용법에 대한 공식 교육이 없다는 사실을 전제로하고 싶다. 이것이 나의 첫 번째 벤처이다. 내 상황에 대해 비슷한 질문을 찾을 수는 없었다.C 유닉스 - fork(), execl()과 파이프를 루프에 넣는다
참고 : 이것은 학교 과제를위한 더 큰 프로젝트의 일부이므로, 나를 위해이 작업을 수행 할 사람을 요청하지는 않습니다. 나는 방향/도움이되는 코드 세그먼트를 원할 것이다. (I는 "사기꾼"발언을 피하기 위해 가능한 한이 같은 일반 만들기 위해 노력했다.)
내가 부모 프로세스가 fork()
및 execl()
와 k
어린이를 소재로 급부상하는 for-loop
int k
이상의 요소를 실행하고 사용하는 것을 시도하고있다 pipe()
을 사용하여 출력을 상위로 다시 보냅니다.
참고 : 여기가 발생하는 내가 사용하려고 몇 가지 일반적인 코드와 오류/문제 helloworld
가 생산 GCC
로 컴파일 된 실행 파일을 =이 printf("hello world\n");
int k = 10; //The number of children to make
int fd[2]; //Used for each pipe
int readFromMe[k]; //Holds the file IDs of each pipe fd[0]
int writeToMe[k]; //Holds the file IDs of each pipe fd[1]
int processID[k]; //Holds the list of child process IDs
//Create children
int i;
for(i = 0; i < k; i++)
{
if(pipe(fd) == -1)
{
printf("Error - Pipe error.\n");
exit(EXIT_FAILURE);
}
//Store the pipe ID
readFromMe[i] = fd[0];
writeToMe[i] = fd[1];
if((processID[i] = fork()) == -1)
{
fprintf(stderr, "fork failure");
exit(EXIT_FAILURE);
}
//If it is a child, change the STDOUT to the pipe-write file descriptor, and exec
if(processID[i] == 0)
{
dup2 (writeToMe[i], STDOUT_FILENO);
close(readFromMe[i]);
execl("./helloworld", (char *)0);
}
//If it is the parent, just close the unnecessary pipe-write descriptor and continue itterating
else
{
close(writeToMe[i]);
}
}
//Buffer for output
char output[100000];
//Read from each pipe and print out the result
for(i = 0; i < k; i++)
{
int r = read(readFromMe[i], &output, (sizeof(char) * 100000));
if(r > 0)
{
printf("result = %s\n", output);
}
close(readFromMe[i]);
}
나는로부터 출력을 얻을 내 프로그램이 전혀 없기 때문에이 문제가 발생하는 이유를 파악하려고합니다.
exec가 성공하는지 확인하고 read가 0 또는 -1을 반환하는지 확인하고 -1이면 errno를 확인하십시오. –
execl이 확실히 문제를 일으켰습니다. – MrHappyAsthma