Help needed Write a C program called lastnameTripletsExtended by accepting any n
ID: 3571881 • Letter: H
Question
Help needed
Write a C program called lastnameTripletsExtended by accepting any number of integer parameters (USe malloc() fn).
The program (parent process= P) should create 3 children, C1, C2, and C3, sequentially.
C1 should print its PID, then calculate and print the sum of the integers.
C2 should print its PID, then calculate and print the product of the integers.
C3 should print its PID, then calculate and print the sum the squares of the integers. The parent should wait for all three children to complete their calculations before printing its own PID and exiting.( Only the parent process should create children. )
P creates C1 and waits.
C1 performs sum calculation.
C1 exits.
P creates C2 and waits.
C2 performs product calculation.
C2 exits.
P creates C3 and waits.
C3 performs sum of squares calculation.
C3 exits.
P exits.
Hint: Use the function atoi() to convert an argument passed in through the command line into an integer.
Explanation / Answer
#include<stdlib.h>
#include<sys/wait.h>
#include<stdio.h>
#include<unistd.h>
int main()
{
int status;
pthread_t tid[3];
int pid;
int a=5;
int b=10;
pid=fork();
pthread_t id = pthread_self();
if(pid<0)
{
printf(" Error ");
exit(1);
}
else if(pid==0)
{
if(pthread_equal(id,tid[0]))
{
printf(" Pid is %d ",getpid());
printf(" Sum is:",a+b);
}
if(pthread_equal(id,tid[1]))
{
printf(" Pid is %d ",getpid());
printf(" Product is:",a*b);
}
if(pthread_equal(id,tid[2]))
{
printf(" Pid is %d ",getpid());
printf(" Sum of squares of both integers is:",(a*a+b*b));
}
exit(0);
}
else
{
wait(&status);
printf(" This is Parent process ");
//following function give the pid of parent only
printf(" Parent Process pid: %d ",getpid());
exit(1);
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.