Академический Документы
Профессиональный Документы
Культура Документы
AOS
Practical 2
Aim : Implement unnamed and named Pipe in C.
Code : Unnamed pipe
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
char comm1[100], comm2[100], temp[100] ;
char prefix[10] = "/bin/";
char para1[10][100], para2[10][100], *pipesym = "PIPE";
int first_comm, i=0, j=0,k=0, comm2_start, ret;
int
fd[2], nbytes;
pid_t childpid;
char **args =malloc(sizeof(char*) * 20);
char **args1 = malloc(sizeof(char*) * 20);
strcpy(comm1,argv[1]);
if (!argv[1] || argc <= 1 ) exit(1);
first_comm = 1;
for(i=1; i< argc; i++)
{
if (!strcmp(argv[i], pipesym))
{
first_comm = 0;
comm2_start = 1;
continue;
}
1
14PGIT014
AOS
if(first_comm)
{
strcpy(para1[j], argv[i]);
j++;
}
else
{
if(comm2_start)
{
strcpy(comm2,argv[i]);
comm2_start = 0;
}
strcpy (para2[k], argv[i]);
k++;
}
}
pipe(fd);
if((childpid = fork()) == -1)
{
perror("fork");
exit(1);
}
if(childpid == 0)
{
2
14PGIT014
AOS
14PGIT014
AOS
14PGIT014
AOS
fd1, fd2;
pid_t childpid;
const char s[2] = " ";
char *named_pipe = malloc(sizeof(char) * 50); ;
printf("Enter Command 1 with parameters:");
fgets(comm1, sizeof(comm1), stdin);
comm1[strlen(comm1)-1] = '\0';
printf("\nEnter Command 2 with parameters:");
fgets(comm2, sizeof(comm2), stdin);
comm2[strlen(comm2)-1] = '\0';
printf("\nEnter named pipe (path):");
scanf("%s", named_pipe);
14PGIT014
AOS
14PGIT014
AOS
}
args2[++k] = NULL;
if((childpid = fork()) == -1)
{
perror("fork");
exit(1);
}
if(childpid == 0)
{
/* Child process writes to named_pipe */
fd1 = open(named_pipe, O_WRONLY);
dup2(fd1, 1);
if ( execvp(cmd1, args1) == -1)
{
strcpy(temp, prefix);
strcat(temp, cmd1);
execvp(temp, args1);
printf("%s\n", "Error in execution of First Command");
exit(2);
}
14PGIT014
AOS
}
else
{
/* Parent process closes up output side of pipe */
fd2 = open(named_pipe, O_RDONLY);
dup2(fd2, 0);
if ( execvp(cmd2, args2) == -1)
{
strcpy(temp, prefix);
strcat(temp, cmd2);
execvp(temp, args2);
printf("%s\n", "Error in execution of Second Command");
exit(2);
}}
return(0);
}
Output :