c - SIGCHLD causing segmentation fault, not going into handler -
i'm trying make simple shell , adding in functionality run processes in background &. in main method have:
int main() { if (signal(sigchld, handle) == sig_err) perror("cannot catch sigchld"); pid_t child = fork(); if (child == 0) execvp(command, arguments); else { if (background == 1) { printf("1"); backgroundlist(command, child); printf("2"); } else waitpid(child, null, 0); } }
and handler have:
void handle(int s) { printf("a"); if (signal(sigchld, handle) == sig_err) perror("cannot catch sigchld"); pid_t pid; printf("b"); while((pid = waitpid(0, null, wnohang)) > 0) { printf("c"); rmbackgroundlist(pid); printf("d"); } }
i can can have run process in foreground fine. running "ls" has contents print screen, "a" , "b" printed since goes sigchld handler, doesn't go "c" since it's been waited on.
however, running in background ("ls&") print "1" , "2", have parent go prompt, child print contents screen, segmentation fault. not print of letters have in handler.
i cannot figure out why sigchld children waited on causes segmentation fault , never goes handler processes not waited on.
you not following rules signal handler. can't use printf()
or perror()
. read rules on safe in signal handler.
also behavior of signal()
changes depending on if it's bsd or sysv style unix. linux changes behavior in glibc based on presence of _bsd_source or _gnu_source , changes depending on if call gcc -ansi
or gcc -std=c99
or gcc -std=gnu99
you should using sigaction()
instead of signal()
.
Comments
Post a Comment