Copy Below C Language Code & Enjoy Using Free KST Learning Code
Code Examples
C
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <ctype.h>
#include <string.h>
int main()
{
int pipe1[2]; // Pipe 1: Parent to Child
int pipe2[2]; // Pipe 2: Child to Parent
pid_t pid;
char studentID[50];
char receivedID[50];
int digitCount = 0;
// Create first pipe
if (pipe(pipe1) == -1)
{
printf("Pipe 1 creation failed!\n");
return 1;
}
// Create second pipe
if (pipe(pipe2) == -1)
{
printf("Pipe 2 creation failed!\n");
return 1;
}
// Create child process
pid = fork();
if (pid < 0)
{
printf("Fork failed!\n");
return 1;
}
// Child Process
else if (pid == 0)
{
// Close unused pipe ends
close(pipe1[1]); // Child does not write to pipe1
close(pipe2[0]); // Child does not read from pipe2
// Read Student ID from Parent Process
read(pipe1[0], receivedID, sizeof(receivedID));
// Count digits in Student ID
for (int i = 0; receivedID[i] != '\0'; i++)
{
if (isdigit(receivedID[i]))
{
digitCount++;
}
}
// Send digit count back to Parent Process
write(pipe2[1], &digitCount, sizeof(digitCount));
// Close used pipe ends
close(pipe1[0]);
close(pipe2[1]);
exit(0);
}
// Parent Process
else
{
// Close unused pipe ends
close(pipe1[0]); // Parent does not read from pipe1
close(pipe2[1]); // Parent does not write to pipe2
// Take Student ID input from user
printf("Enter your Student ID: ");
scanf("%s", studentID);
// Send Student ID to Child Process
write(pipe1[1], studentID, strlen(studentID) + 1);
// Read digit count from Child Process
read(pipe2[0], &digitCount, sizeof(digitCount));
// Wait for Child Process to finish
wait(NULL);
// Display result
printf("\n--- Result ---\n");
printf("Original Student ID : %s\n", studentID);
printf("Total Digits (Child Process) : %d\n", digitCount);
// Close used pipe ends
close(pipe1[1]);
close(pipe2[0]);
}
return 0;
}