Linux and C pipe system call Code for Lab 5 that is mentioned: #include <stdio.h
ID: 3829421 • Letter: L
Question
Linux and C pipe system call
Code for Lab 5 that is mentioned:
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
int main()
{
int shmid, status;
int *a, *b;
int i;
shmid = shmget(IPC_PRIVATE, sizeof(int), 0777|IPC_CREAT);
int *temp=(int *)shmat(shmid,0,0);
*temp=19530;
int start=1;
// for(i=0;i<5;i++)
// {
if (fork() == 0) {
b = (int *) shmat(shmid, 0, 0);
if(start==1)
{b[0]=19530;
start=0;
}
for( i=0; i< 5; i++) {
if(i==0)
b[0]=19530;
sleep(1);
b[0]-=5;
printf(" Child reads: %d ",b[0]);
}
shmdt(b);
}
else {
a = (int *) shmat(shmid, 0, 0);
for( i=0; i< 5; i++) {
sleep(1);
a[0] = a[0]/5;
printf("Parent writes: %d, ",a[0]);
}
wait(&status);
shmdt(a);
shmctl(shmid, IPC_RMID, 0);
}
}
Explanation / Answer
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int main(void)
{
int fd[2], nbytes;
pid_t cpid;
char readbuffer[80];
pipe(fd);
if((cpid = fork()) == -1)
{
perror("fork");
exit(1);
}
if(cpid == 0)
{
for( i=0; i< 5; i++) {
if(i==0)
b[0]=19530;
sleep(1);
b[0]-=5;
printf(" Child reads: %d ",b[0]);
close(fd[0]);
exit(0);
}
else
{
a = (int *) shmat(shmid, 0, 0);
for( i=0; i< 5; i++) {
sleep(1);
a[0] = a[0]/5;
printf("Parent writes: %d, ",a[0])
close(fd[1]);
}
return(0);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.