如何 运行 在 C 中使用 n-command 编程?

How to run program with n-command in C?

我现在已经一一编译了。我也面临着终止进程的问题。

int main(int argc, char *argv[]) {

int n = 1;
int f = 1;

signal(SIG_ERR, sig_hand1);
signal(SIGINT, sig_hand1);

for (f; f < argc; f++){ \create n-numberd fork.
    nfork(f, argv);
}

for (n; n<argc; n++){ \terminate the child one by one.
    Rturn(n, argv);
}
return 0;

}

带回车功能

void Rturn(int n, char *argv[]){

int status;
struct rusage usage;
struct timeval start;
struct timeval end;
wait4(-1, &status, 0, &usage);
if(WIFSIGNALED(status)==1){
        char *str = strdup(signame[WTERMSIG(status)]);
        printf("\nThe command %c%s%c is interrupted by the %s\n\n", '"', argv[n], '"',str);
    }
    else if(WEXITSTATUS(status) == 255)
        printf("The program experienced an error in starting the command: %s\n\n", argv[n]);
    else
        printf("\nThe command %c%s%c terminated with returned status code = %d\n\n", '"', argv[n], '"', WEXITSTATUS(status));

}

和 nfork

void nfork(int n, char *argv[]){
if(fork() == 0){
    printf("Process with id:%d created for the command: %s\n", getpid(), argv[n]);
    fflush(stdout);
    if(execlp(argv[n], argv[n], NULL) == -1){
        printf("\nexeclp:  %s\n\n", strerror(errno));
        exit(-1);
    }
}

}

我发现消息不是由进程 return 编辑的,而是由循环中的 n 编辑的。

例如,如果我 运行

./test cd fake //with command cd and "fake"

然后会return

monitor experienced an error in starting the command: cd

预期的return应该是这样的

monitor experienced an error in starting the command: fake

如何找到变量 n 的正确子项?

成功时,fork() 函数 return 执行两次。在parent进程中,其return值是新child的进程ID。在child进程中,return值为0,parent正是通过return给它的进程ID来识别特定的children所以至于等待他们,给他们发信号,etc..

您的 nfork() 函数目前忽略 fork() 的 return 值,除了检查它是否为零。这是错误的,原因有二:

  1. parent不区分fork()调用的成功与失败。它只是假设它成功了。

  2. parent 希望稍后能够将特定的 children 与 n 的相应值相关联。各个进程由它们的进程 ID 标识。只有在 nfork() 中才有机会将 child 进程 ID 与 n 值相关联,但函数无法利用它。

有许多方法可以记录 child 索引和 child 进程 ID 之间的关联,但最简单的可能是创建一个数组来存储它们。 nfork() 需要填充数组,而 RTurn() 需要从中提取要等待的 PID,然后将其作为第一个参数提供给 wait4()