4
Launch a child process and kill it
- /*
- * Forks and kills child.
- *
- * fork
- * kill
- * wait
- * WIFEXITED
- * WEXITSTATUS
- * WTERMSIG
- * getpid
- * sleep
- */
- #include <sys/types.h>
- #include <sys/wait.h>
- #include <signal.h>
- #include <unistd.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <errno.h>
- #if defined( LINUX )
- #include <string.h>
- #endif
- #define SLEEPTIME 2 /* in secs */
- int main(int argc, char *argv[]) {
- int pid, status, died;
- int killer = 0;
- switch (argc) {
- case 2:
- if (strcmp(argv[1], "-k") != 0)
- goto usage;
- killer = 1;
- break;
- case 1:
- break;
- default:
- usage: fprintf(stderr, "%s [-k]\n", argv[0]);
- exit(1);
- }
- fprintf(stdout, "%i running...\n", getpid());
- pid = fork();
- if (pid == -1) { /* error */
- fprintf(stderr, "%s\n", strerror(errno));
- exit(1);
- }
- if (pid == 0) { /* child */
- fprintf(stdout, "%i sleeping for %i secs...\n", getpid(), SLEEPTIME);
- sleep(SLEEPTIME);
- /* exit with an error half the time */
- exit(getppid() & 1);
- }
- /* kill child? */
- if (killer) {
- fprintf(stdout, "%i killing %i...\n", getpid(), pid);
- kill(pid, SIGKILL);
- }
- /* wait for child */
- fprintf(stdout, "%i waiting for %i...\n", getpid(), pid);
- died = wait(&status);
- if (WIFEXITED(status))
- fprintf(stdout, "%i exited with status %i\n", died, WEXITSTATUS(status));
- else
- fprintf(stdout, "%i killed with signal %i\n", died, WTERMSIG(status));
- fprintf(stdout, "%i bye\n", getpid());
- exit(0);
- }
Comments