Write a Unix C program using the fork() system call that generates the factorial and gives a sequence of series like 1, 2, 6, 24, 120… in the child process.
The number of the sequence is provided in the command line.
Input :gfg@ubuntu:~/$ gcc -o fork fork.c gfg@ubuntu:~/$ ./fork 6 Output :1 1 2 1 2 6 1 2 6 24 1 2 6 24 120 1 2 6 24 120 720 After deletion sum 1 3 9 33 153 873 Done Input :gfg@ubuntu:~/$ gcc -o fork fork.c gfg@ubuntu:~/$ ./fork -2 Output :negative number entered -2
To create child process fork()is used. fork() returns :
- < 0 fail to create child (new) process
- = 0 for child process
- > 0 i.e process ID of the child process to the parent process. When >0 parent process will execute.
Inside Child process: If input is 6, the first six numbers of the factorial sequence will be given as output by the child process. Because the parent and child processes have their own copies of the data, it will be necessary for the child to output the sequence.
Inside Parent process: The parent invokes the wait () call to wait for the child process to complete before exiting the program. Perform necessary error checking to ensure that a non-negative number is not passed on the command line.
Compiling Code code saved with name fork.c
gfg@ubuntu:~/$ gcc -o fork fork.c
gfg@ubuntu:~/$ ./fork 5
1 1 2 1 2 6 1 2 6 24 1 2 6 24 120 After deletion sum 1 3 9 33 153 Done
Firstly, command line argument is accepted. Then the number of arguments are passed and checked if the argument is positive.
After that, generate the factorial series.
Related Article- C program to demonstrate fork() and pipe()
This article is contributed by Kartik Ahuja. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Calculation in parent and child process using fork()
- Algorithm for Dynamic Time out timer Calculation
- First digit in factorial of a number
- fork() in C
- 8085 program to find the factorial of a number
- 8086 program to find the factorial of a number
- searching in fork()
- sorting in fork()
- fork() and Binary Tree
- Fork() - Practice questions
- C vs BASH Fork bomb
- Difference between fork() and exec()
- C program to demonstrate fork() and pipe()
- Creating multiple process using fork()