/*
* mysystem.c
*/
#include <stdio.h>
#include "csapp.h"
int mysystem(char* command) {
pid_t pid;
int status;
if ((pid = Fork()) == 0) {
/* child process */
char* argv[4] = { "", "-c", command, NULL };
execve("/bin/sh", argv, environ);
}
/* print child pid so we can kill it */
printf("child pid: %d\n", pid);
if (Waitpid(pid, &status, 0) > 0) {
/* exit normally */
if (WIFEXITED(status))
return WEXITSTATUS(status);
/* exit by signal */
if (WIFSIGNALED(status))
return WTERMSIG(status);
}
}
int main(int argc, char* argv[]) {
int code;
code = mysystem("./exit-code");
printf("normally exit, code: %d\n", code); fflush(stdout);
code = mysystem("./wait-sig");
printf("exit caused by signal, code: %d\n", code); fflush(stdout);
return 0;
}
when running ./mysystem
, it runs ./exit-code
/*
* exit-code.c
*/
#include "csapp.h"
int main(int argc, char* argv[]) {
exit(10);
}
should output
normally exit, code 10
and runs ./wait-sig
, stuck here
/*
* wait-sig.c
*/
#include "csapp.h"
int main(int argc, char* argv[]) {
while (1);
}
fall into dead loop. open another terminal, type
kill -<n> <wait-sig's pid>
./mysystem
will return and output
exit caused by signal, code <n>