I have been tasked with writing a C program which allows the child code to finish after the parent, using the sleep command.
This is what I have written, the code does not work and it only returns the 'else' part of the code. If anyone could help it would be much appreciated. I believe the problem is how I have used the sleep command.
#include <stdio.h>
#include <unistd.h>
int main() {
fork();
if (fork() ==0){
sleep(5);
printf("This will finish after the parent\n");
}
else
printf("This will finish before the child\n");
return 0;
}
try to use the pid instead of fork() twice
#include <stdio.h>
#include <unistd.h>
int main() {
pid_t pid=fork();
if (pid==0){
sleep(5);
printf("This will finish after the parent\n");
}
else
printf("This will finish before the child\n");
return 0;
}
This is what I came up with, but it is somewhat hard to tell which is the child class and the parent class.
int main() {
fork();
if (fork() ==0){
// sleep(5);
printf("This will finish after the parent\n");
}
else
{
sleep(5);
printf("This will finish before the child\n");
}
return 0;
}
Fork system call is used for creating a new process.parent process and child process.the child get pid==0,but the parent get pid==(to the main pid of the child).
#include <stdio.h>
#include <unistd.h>
int main() {
pid_t pid=fork();
if (pid==0){
sleep(5);
printf("This will finish after the parent\n");
printf("child pid is %d\n",getpid());//get the current process pid
}
else
{
printf("This will finish before the child\n");
printf("child pid is %d\n",pid);
}
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.