Hi friends,
First I am going to type the c program, then we will discuss it.
1 #include <sys/types.h>
2 #include <stdio.h>
3 #include <unistd.h>
4
int main()
5 {
6 pid_t pid;
7
/* fork a child process */
8 pid = fork();
9
10 if(pid<0)
11 { /* error occured */
12 fprintf(stderr, "\Fork Failed\n");
13 exit(-1);
14 }
15 else if(pid==0)
16 { /* child process */
17 execlp("/bin/ls","ls",NULL);
18 }
19 else
20 { /* parent process */
/* parent will wait for the child to complete */
21 wait(NULL);
22 printf("\nChild complete\n");
23 exit(0);
24 }
25 }
And here comes my questions
- Why does
pid
variable contain two values, or how could it have two values, less than 0, equal to 0, and greater than zero. They say fork() returns different values for parent process and child process. but how is it possible for one variable to hold two values at the same time?
2. Please explain the syntax of
execlp("/bin/ls","ls",NULL);
. What does it get NULL at the end?
3. Syntax of exit()???. Somestimes it gets -1, 0 and EXIT_FAILURE and things like that.
4. What does wait() do, why is it taking NULL argument here?
And here is a another program
1 #include <stdio.h> /* printf, stderr, fprintf */
2 #include <sys/types.h> /* pid_t */
3 #include <unistd.h> /* _exit, fork */
4 #include <stdlib.h> /* exit */
5 #include <errno.h> /* errno */
6 int main()
7 {
8 pid_t pid;
9 pid = fork();
10 if(pid == -1)
11 {
12 fprintf(stderr, "can't fork, error %d\n", errno);
13 exit(EXIT_FAILURE);
14 }
15 if(pid == 0)
16 {
17 int j;
18 for(j = 0;j<10;j++)
19 {
20 printf("child: %d\n", j);
21 sleep(1);
22 }
23 _exit(0);
24 }
25 else
26 {
27 int i;
28 for(i = 0;i<10;i++)
29 {
30 printf("parent: %d\n",i);
31 sleep(1);
32 }
33 exit(0);
34 }
35 return 0;
36 }
And it's output
$ ./fork
child: 0
parent: 0
child: 1
parent: 1
child: 2
parent: 2
child: 3
parent: 3
child: 4
parent: 4
child: 5
parent: 5
child: 6
parent: 6
child: 7
parent: 7
child: 8
parent: 8
child: 9
parent: 9
- Why and how there is a switching between child process and parent process?
- What is the different between exit() and _exit()
And a small program as well,
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
int main()
{
pid_t pid;
pid = fork();
printf("%d\n",pid);
return 0;
}
And here is the output
$ ./fork4
0
1055
Why does the second value, 1055 gets printed, I didn't use printf to print this value, where did it come from? And if I remove the printf function from this program, like
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
int main()
{
pid_t pid;
pid = fork();
return 0;
}
then there is no output at all, why is that so?
Please bear with my nonsensical questions, I am an absolute novice???
Looking forward to your kind and helpful replies!
You guys rock!
Thanks