簡體   English   中英

如何在C中使用n命令運行程序?

[英]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;

}

使用 Rturn 功能

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);
    }
}

}

我發現消息不是由進程返回,而是由循環中的 n 返回。

例如,如果我運行

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

然后它會返回

monitor experienced an error in starting the command: cd

預期回報應該是這樣的

monitor experienced an error in starting the command: fake

如何找到變量 n 的正確子級?

成功時, fork()函數返回兩次。 在父進程中,它的返回值是新子進程的進程ID。 在子進程中,返回值為0。通過返回給它的進程ID,父進程可以識別特定的子進程,從而等待他們,向他們發送信號

您的nfork()函數目前忽略fork()的返回值,只是檢查它是否為零。 這是錯誤的,原因有二:

  1. 父級不區分fork()調用的成功和失敗。 它只是假設它成功了。

  2. 父級希望能夠稍后將特定子級與n的相應值相關聯。 各個進程由其進程 ID 標識。 只有在nfork()中有機會將子進程 ID 與n 個值相關聯,但該函數未能利用它。

有多種方法可以記錄子索引和子進程 ID 之間的關聯,但最簡單的方法可能是創建一個數組來存儲它們。 nfork()需要填充該數組,而RTurn()將需要從中提取要等待的PID,然后將其作為第一個參數提供給wait4()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM