diff options
Diffstat (limited to 'dev/c/src/fork')
-rw-r--r-- | dev/c/src/fork/Makefile | 11 | ||||
-rw-r--r-- | dev/c/src/fork/fork.c | 38 | ||||
-rw-r--r-- | dev/c/src/fork/fork_exec.c | 40 |
3 files changed, 89 insertions, 0 deletions
diff --git a/dev/c/src/fork/Makefile b/dev/c/src/fork/Makefile new file mode 100644 index 0000000..a737794 --- /dev/null +++ b/dev/c/src/fork/Makefile @@ -0,0 +1,11 @@ + +progs=fork fork_exec +all: $(progs) + +fork: fork.c + +fork_exec: fork_exec.c + + +clean: + rm $(progs) diff --git a/dev/c/src/fork/fork.c b/dev/c/src/fork/fork.c new file mode 100644 index 0000000..25e4909 --- /dev/null +++ b/dev/c/src/fork/fork.c @@ -0,0 +1,38 @@ + +#include <sys/types.h> +#include <sys/wait.h> +#include <stdio.h> +#include <stdlib.h> +#include <unistd.h> +#include <errno.h> +#include <string.h> + +int main(){ + + pid_t cpid,ppid; + char errbuf[1024]; + + cpid = fork(); + if (cpid == -1) { + (void) snprintf(errbuf, sizeof(errbuf), + "fork: %s", strerror(errno)); + printf("%s\n", errbuf); + exit(1); + } + + if (cpid == 0) { + //child + ppid = getppid(); + if(ppid == 1){ + printf("parent died ?\n"); + _exit(1); + } + printf("I'm child with %i, parent %i\n", getpid(), ppid); + _exit(0); + } +/* parent */ + wait(NULL); + printf("Child id: %i\n", cpid); + return 0; +} + diff --git a/dev/c/src/fork/fork_exec.c b/dev/c/src/fork/fork_exec.c new file mode 100644 index 0000000..7f87c84 --- /dev/null +++ b/dev/c/src/fork/fork_exec.c @@ -0,0 +1,40 @@ +#include <sys/types.h> +#include <sys/wait.h> +#include <stdio.h> +#include <stdlib.h> +#include <unistd.h> +#include <errno.h> +#include <string.h> + +int main(){ + + pid_t cpid,ppid; + char errbuf[1024]; + + char *prog = "vim"; + char *const args[3]= {"vim", "fork_exec.c", NULL}; + + cpid = fork(); + if (cpid == -1) { + (void) snprintf(errbuf, sizeof(errbuf), + "fork: %s", strerror(errno)); + printf("%s\n", errbuf); + exit(1); + } + + if (cpid == 0) { + //child + ppid = getppid(); + if(ppid == 1){ + printf("parent died ?\n"); + _exit(1); + } + execvp(prog, args); + _exit(0); + } +/* parent */ + wait(NULL); + printf("Child id: %i\n", cpid); + return 0; +} + |