[英]How does parent process get the termination status through wait from a child process which calls _exit
[英]How to set status termination of a process C?
我的程序是基本的小外殼。 它允許您以參數ls,cd ...的形式在PATH中運行程序。 要從終端“ ./myshell2”運行程序類型,它將啟動,您可以插入所需的命令數量。
它啟動一個子進程,運行execvp,返回並重新啟動,因此您可以鍵入新命令。 當鍵入“ Q”或“ q”時,整個程序應終止。 問題是我不知道如何停止它,下面的代碼。 我的想法是,當鍵入“ Q”或“ q”時,殺死所創建的子進程並發送信號以消除其錯誤終止(子進程)。 因此(來自父項的)最終狀態將不是1,並且該函數返回。 我評論了代碼的某些部分,希望它更容易理解。 它起作用的問題是要停止它,我需要ctrlC。我想對子進程說,他必須以一個非零值結尾。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>
#include <signal.h>
int main(int argc, char * argv[]) {
while(1)
{
pid_t pid = fork();
if (pid == -1) {
perror("fork error");
exit(EXIT_FAILURE);
}
if (pid == 0) { // child process
printf("type the command to start (and arguments if required) \n"
"Q to quit\n");
char *dest[10]; // allow you to insert
char line[4096];//commands from terminal
if (fgets(line,sizeof(line),stdin)==0) return 1;
int i;
line[strcspn(line, "\n")] = '\0';
char *st = line;
for (i=0; i< 10 && (dest[i]=strsep(&st," "))!=NULL;i++)
continue;//now you typed the command
if ( ( memcmp(dest[0],"Q",1)==0 ) // if Q or q the program
|| (memcmp(dest[0],"q",1)==0) ) //must end
{
printf("got it!\n");
if (kill(getpid(),SIGSEGV)==-1) printf("kill error\n");
//in theory the process should terminates with bad status
// and the value of the variable "status" 'll be not 0
// I think that the problem is in this part of the code
}
if( strcmp(dest[0]," ")!=0 )
{
int res = execvp(dest[0], dest);
}
else
{ int res= execvp(dest[1],dest+1);}
perror("execvp error");
exit(EXIT_FAILURE);
}
int status;
pid_t child = wait(&status);
if (child == -1) {
perror("wait error");
exit(EXIT_FAILURE);
}
if (status==1)
break; //so it can exit from the loop that creates new process
setenv("WAIT","TRUE",0); //dont' worry about
//perror("setenv error\n");
if (memcmp("TRUE",getenv("WAIT"),4) == 0 ) //these 6 lines
printf("WAIT=TRUE\n");
else if(memcmp("FALSE",getenv("WAIT"),4) == 0 )
printf("WAIT=FALSE\n");
printf("end current process (status=%d, child=%d)\n", WEXITSTATUS(status), son);
}
return EXIT_SUCCESS;
}
您正在為所有情況打印WEXITSTATUS()
,但這是不對的。 您需要使用WIFEXITED()
檢查wait
返回的狀態是否為退出狀態。 如果非零,則孩子正常退出。 否則,您可以使用WIFSIGNALED()
查看該子項是否已終止,並且您將從WTERMSIG()
獲得信號
if(WIFEXITED(status))
{
printf("end current process (status=%d, child=%d)\n", WEXITSTATUS(status), son);
}
else if(WIFSIGNALED(status))
{
printf("end current process (signal=%d, child=%d)\n", WTERMSIG(status), son);
}
您確實應該讓父進程處理命令的輸入,而讓子進程運行它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.