c - How to terminate a program from a child process? -
i trying terminate program takes line full of commands file , process each command using execvp
however,whenever encounter quit
, want exit processing commands , ignore other commands coming after it.
i tried following way using exit()
for(int =0;i < numofcommands;i++) { childpid = fork(); if(childpid == 0) { if(execvp(commands[i].cmd[0],commands[i].cmd) == -1) { /*if(strcmp(commands[i].cmd[0],"quit")) { done = true; return; }*/ if(strcmp(commands[i].cmd[0],"quit")==0) { printf("quit command found ! \n quitting ."); done = true; //return; exit(0); } printf("command %s unknown \n", commands[i].cmd[0]); } } else { //parent process wait(&child_status); } } }
and happens inside of child process, after forking of course. problem program keeps processing remaining commands comes after quit before exiting program !
i think better way deal check quit
command in parent process before forking child.
but if want in child, can send signal parent.
kill(getppid(), sigusr1);
the parent process need establish signal handler sigusr1
cleans , exits. or send signal sigint
, default action kill process, it's better implement clean exit.
also, in code, should check quit
command before calling execvp
. otherwise, if there's quit
program in user's path, never match built-in quit
, since execvp
succeed , not return.
Comments
Post a Comment