[英]Processes, fork, pipes program…Where am I going wrong?
I'm working in Unix and I'm trying to write a .c file that will do the following: 我正在Unix上工作,并且试图编写一个.c文件来执行以下操作:
For each command line argument the main process will launch a subprocess (type A). 对于每个命令行参数,主进程将启动一个子进程(类型A)。
The A process will try to execute, in a new subprocess (type B), using one of the exec functions, the received argument. A进程将尝试使用exec函数之一在新的子进程(类型B)中执行接收到的参数。
In case of failure, the process of type A, will send to his parent, using a pipe channel, the error code (errno value) generated by the exec call. 如果失败,类型A的进程将使用管道通道将exec调用生成的错误代码(errno值)发送给其父级。
On success, the process A, will wait for process of type B and once finished it will transmit to his parent the zero code, using the same pipe channel. 成功后,进程A将等待类型B的进程,一旦完成,它将使用相同的管道通道将零代码发送给其父级。
The main process will print for each argument if the execution was successful or not. 如果执行成功与否,将为每个参数打印主进程。 Only for failed executions the error received code will be printed too.
仅对于失败的执行,也会打印收到的错误代码。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
int main(int argc, char const *argv[]) {
int c2p[2], g2c[2];
int i;
char n[100];
int *stat;
for (i = 0; i < argc; i++ ) {
pipe(c2p);
pipe(g2c);
if (fork() == 0) {
//child code
if (fork() == 0) {
//grandchild code
if (execlp("argv[i]", "argv[i]", NULL) == -1) {
write(g2c[1], errno, sizeof(int));
} else {
write(g2c[1], 0, sizeof(int));
}
}
wait(0);
read(g2c[0], n, 10);
write(c2p[1], n, 10);
exit(0);
}
read(c2p[0], &stat, sizeof(int));
if (*stat !=0) {
printf("Not succsesful: %s %d\n", argv[i], *stat);
} else {
printf("Succes! %s\n", argv[i]);
}
}
return 0;
}
Changed your code as follow and this would worked for you: 如下更改您的代码,这将为您工作:
int main(int argc, char const *argv[])
{
int c2p[2];
int i;
int stat;
for (i = 1; i < argc; i++ ) {
pipe(c2p);
if (fork() == 0) {
//child code
if (fork() == 0) {
//grandchild code
if (execlp(argv[i], argv[i], NULL) == -1)
exit(errno);
}
wait(&stat);
write(c2p[1], &stat, sizeof(stat));
exit(0);
}
read(c2p[0], &stat, sizeof(int));
if (stat != 0)
printf("Not succsesful: %s %d\n", argv[i], stat);
else
printf("Succes! %s\n", argv[i]);
}
}
as you see in my code: 如您在我的代码中看到的:
Two problems: 两个问题:
int n; ...; write(fd, &n, sizeof n);
int n; ...; write(fd, &n, sizeof n);
int n; ...; write(fd, &n, sizeof n);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.