The contents of this page are licensed under the following license
Operating System
Create a child process |
#include <sys/types.h> #include <unistd.h> #include <stdio.h> int main(int argc, char* argv[]) { int pid1, ppid1, pid2, ppid2; int status; pid1 = getpid(); ppid1 = getppid(); printf("Start\n"); /* create a child process */ switch (fork()) { case -1:/* error */ perror("fork - can't create process"); break; case 0 :/* child process */ pid2 = getpid(); ppid2 = getppid(); printf("Process: %d, Parent: %d\n", pid2, ppid2); sleep(5); break; default:/* parent process */ printf("Process: %d, Parent: %d\n", pid1, ppid1); wait(&status); printf("End (status = %d)\n", status); } } |
Executing programs within programs and redirecting standard streams |
#include <sys/types.h> #include <unistd.h> #include <stdio.h> #include <fcntl.h> #include <stdlib.h> int main(int argc, char* argv[]) { int fd, ppid; /* close standard output */ close(1); /* open file */ fd = open("results.txt", O_CREAT | O_WRONLY | O_APPEND, 0644); if (fd == -1) { perror("Error open file"); exit(1); } /* create a child process */ if ((ppid = fork()) == 0) { /* execute ls command */ execlp("ls", "ls", "-l", "-a", "-i", NULL); } waitpid(ppid, NULL, NULL); } |
November, 29th 2006 © Michał Kalewski