modify this program so that it used clone instead of fork. the output should be
ID: 3824474 • Letter: M
Question
modify this program so that it used clone instead of fork.
the output should be
This is process(thread) 11501.
x+y=1
>
This is process(thread) 11502.
x+y=7
//fork makes a second process, running the same executable
//pid_t used to be long, but now just int
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main ( void ) {
int x=0, y=0;
pid_t pid, fpid;
fpid = fork ();
pid = getpid();
if (fpid > 0){
printf (" This is process(thread) %d. ",pid);
y=1;
}
else if (fpid == 0){
sleep(1);
printf (" This is process(thread) %d. ",pid);
x=7;
}
else {
printf ("fork failed ");
return (1);
}
printf("x+y=%d ",x+y);
}
Explanation / Answer
Program that shows how fork system call works
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
int main(void)
{
pid_t pid;
char cwdir_cld[100];
char cwdir_prt[100];
if ((pid = fork()) < 0) {
perror("fork error");
exit(1);
}
if (pid == 0) {
/*
* Now we are in the childs thread
* let us issue a chdir syscall :)
*/
if(chdir("/tmp") < 0) {
perror("chdir error");
}
/*
* Let us now print the current working directory of the child
*/
if (getcwd(cwdir_cld, 100) != NULL) {
printf("
Current working directory of the child is : %s", cwdir_cld);
} else {
perror("
getcwd error");
}
/* end of the child */
} else {
/*
* Now we are in the parent thread
* Let is check the current working directory
*/
if (getcwd(cwdir_prt, 100) != NULL) {
printf("
Current working directory of the parent is : %s", cwdir_prt);
} else {
perror("
getcwd error");
}
}
printf("
");
return(0);
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.