this is my c code. i created 2 child processes. but i do not know how to solve b
ID: 3863048 • Letter: T
Question
this is my c code.
i created 2 child processes.
but i do not know how to solve below requirements...
can you add some codes for me? thanks
1. Write a series of small C programs
if a file read.txt is opened by a parent and kept open across a call to fork, is read.txt still open in the child process? If the answer is yes, when a child process reads blocks from read.txt, will the parent remain at the same position in read.txt? Write a series of small C programs
int main()
{
int fd;
pid_t pid;
pid = fork();
if (pid < 0)
{
fprintf(stderr, "Error");
exit(EXIT_FAILURE);
}
//child 1
else if (pid == 0)
{
printf("I am child 1. ");
}
else
{
pid = fork();
// child 2
if (pid == 0)
{
printf("I am child 2. ");
}
else
{
wait (NULL);
exit(EXIT_SUCCESS);
}
}
}
Explanation / Answer
If a file read.txt is opened by a parent and kept open across a call to fork, is read.txt still open in the child process?
Yes
==========
Use the below code
==========
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{
FILE *fp;
char buff[255];
fp = fopen("read.txt","r");
int fd;
pid_t pid;
printf("I am Parent ");
fgets(buff, 255, (FILE*)fp);
printf("1: %s ", buff );
pid = fork();
if (pid < 0)
{
fprintf(stderr, "Error");
exit(EXIT_FAILURE);
}
//child 1
else if (pid == 0)
{
printf("I am child 1. ");
fgets(buff, 255, (FILE*)fp);
printf("2: %s ", buff );
}
else
{
printf("I am Parent ");
fgets(buff, 255, (FILE*)fp);
printf("3: %s ", buff );
pid = fork();
// child 2
if (pid == 0)
{
printf("I am child 2. ");
fgets(buff, 255, (FILE*)fp);
printf("4: %s ", buff );
}
else
{
wait (NULL);
exit(EXIT_SUCCESS);
}
printf("I am Parent ");
fgets(buff, 255, (FILE*)fp);
printf("5: %s ", buff );
}
fclose(fp);
}
=======================
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.