I'm using this code to try to implement my own pipe in a simple shell. However, it won't compile because it's telling me fd is not a function. Every other place I've seen this implemented has fd as the parameter for pipe() in the exact same way. I'm not sure why I'm getting this error.
int startProcess (StringArray sa)
{
int pid;
int status;
int fd1;
int fd2;
int current_in;
int current_out;
int fd0;
int fd00;
int in = 0;
int out = 0;
char input[64]="";
char output[64]="";
char cmd1[64] ="";
char cmd2[64] ="";
int pipe = 0;
int fd[2];
switch( pid = fork()){
case -1://This is an error
perror("Failure of child.");
return 1;
case 0: // This is the child
// Redirection
/* finds where '<' or '>' or '|' occurs and make that sa[i] = NULL ,
to ensure that command wont' read that*/
for(int i=0;sa[i]!='\0';i++)
{
if(strcmp(sa[i],"<")==0)
{
sa[i]=NULL;
strcpy(input,sa[i+1]);
in=2;
}
if(strcmp(sa[i],">")==0)
{
sa[i]=NULL;
strcpy(output,sa[i+1]);
out=2;
}
if(strcmp(sa[i],"|")==0)
{
sa[i]=NULL;
strcpy(cmd1,sa[i-1]);
strcpy(cmd2,sa[i+1]);
pipe=2;
}
}
//if '<' char was found in string inputted by user
(erased for brevity)
//if '>' char was found in string inputted by user
(erased for brevity)
//if '|' char was found in string inputted by user
if(pipe)
{
pipe(fd);
if (!fork)
{
close(1);
dup(fd[1]);
close(fd[0]);
int error;
error = 0;
if (fork() == 0){
error = execvp(cmd1, sa);
} if (error == -1) {
printf("ERROR: unknown command (%s)\n)", cmd1);
exit(0);
} else {
waitpid(0,NULL,0);
}
}
} else {
close(0);
dup(fd[0]);
close(fd[1]);
execvp(cmd2, sa);
}
execvp(sa[0], sa);
perror("execvp");
_exit(1);
printf("Could not execute '%s'\n", sa[0]);
default:// This is the parent
wait(&status);
return (status == 0) ? 0: 1;
}
}
First you have
int pipe = 0;
Then you also have
pipe(fd);
Both can't be correct.
I suggest you rename the variable.
Related
I am trying to learn processes in C and I thiiink I understood the logic of pipe, but can't understand fifo, even if I read a lot about it. I recently made a program using pipe that takes a string from standard input, writes it in pipe1, checks if it's alphanumeric and if so, pipe3 reads it and shows it. If the string only contains digits, pipe2 reads it and replaces digits with _, then pipe4 reads the new string and shows it.
I'm putting it here, because I want to make something similar using fifo:
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<string.h>
#include<sys/wait.h>
#include<ctype.h>
int main()
{
int p1[2];
int p2[2];
int p3[2];
int p4[2];
char input_str[100];
pid_t fork1;
pid_t fork2;
if (pipe(p1)==-1)
{
fprintf(stderr, "Pipe Failed" );
return 1;
}
if (pipe(p2)==-1)
{
fprintf(stderr, "Pipe Failed" );
return 1;
}
if (pipe(p3)==-1)
{
fprintf(stderr, "Pipe Failed" );
return 1;
}
if (pipe(p4)==-1)
{
fprintf(stderr, "Pipe Failed" );
return 1;
}
scanf("%s", input_str);
int isAlpha = 0;
int onlyDigits = 0;
for (int i=0; input_str[i]!= '\0'; i++)
{
if (isalpha(input_str[i]) != 0) {
isAlpha = 1;
onlyDigits = 0;
}
else if (isdigit(input_str[i]) != 0) {
isAlpha = 1;
onlyDigits = 1;
}
else {
isAlpha = 0;
onlyDigits = 0;
}
}
fork1 = fork();
if (fork1 < 0)
{
fprintf(stderr, "fork Failed" );
return 1;
}
else if (fork1 > 0)
{
close(p1[0]);
write(p1[1], input_str, strlen(input_str)+1);
}
else
{
close(p1[1]);
char string_from_p1[100];
read(p1[0], string_from_p1, 100);
close(p1[0]);
fork2 = fork();
if (onlyDigits) {
for (int i=0; string_from_p1[i]!= '\0'; i++) {
if (isdigit(string_from_p1[i]) != 0)
string_from_p1[i] = '_';
}
write(p2[1], string_from_p1, strlen(string_from_p1)+1);
}
else if (isAlpha) {
write(p3[1], string_from_p1, strlen(string_from_p1)+1);
}
if (fork2 < 0) {
fprintf(stderr, "fork Failed" );
return 1;
}
else if (fork2 > 0) {
char string_from_p2[100];
char string_from_p3[100];
char string_from_p4[100];
if (onlyDigits) {
close(p2[1]);
read(p2[0], string_from_p2, 100);
close(p2[0]);
write(p4[1], string_from_p2, strlen(string_from_p2)+1);
close(p4[1]);
read(p4[0], string_from_p4, 100);
printf("String from pipe4: %s\n", string_from_p4);
}
else if (isAlpha) {
close(p3[1]);
read(p3[0], string_from_p3, 100);
printf("String from pipe3: %s\n", string_from_p3);
}
}
exit(0);
}
}
Not sure how correct that is, but the FIFO program will only have 3 processes, it first reads from standard input lines of max 30 characters, writes in first exit (process2) the digits and in second exit (process3) the letters. then in process2 only shows the result (digits found), and in process3 turns small letters into capital letters and shows the result.
Can someone please help me?
As a starting point you could try something like this (most of the functions needs still to be implemented, see comments):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <ctype.h>
void read_and_write(const char *digits_fifo, const char *chars_fifo);
pid_t spawn_digits_child(const char *digits_fifo);
pid_t spawn_chars_child(const char *chars_fifo);
void digits_child(const char *digits_fifo);
void chars_child(const char *chars_fifo);
void wait_until_children_finish(pid_t pid1, pid_t pid2);
#define MAX_INPUT 30
int main() {
char *digits_fifo = "/tmp/digits_fifo";
char *chars_fifo = "/tmp/chars_fifo";
mkfifo(digits_fifo, 0666);
mkfifo(chars_fifo, 0666);
//fork digits process
pid_t pid_digits = spawn_digits_child(digits_fifo);
//fork chars process
pid_t pid_chars = spawn_chars_child(chars_fifo);
//parent
read_and_write(digits_fifo, chars_fifo);
wait_until_children_finish(pid_digits, pid_chars);
exit(0);
}
pid_t spawn_digits_child(const char *digits_fifo) {
pid_t pid1;
if ((pid1 = fork()) < 0) {
fprintf(stderr, "fork error digits process\n");
exit(-1);
} else if (pid1 == 0) {
digits_child(digits_fifo);
exit(0);
}
return pid1;
}
pid_t spawn_chars_child(const char *chars_fifo) {
//do sth similar then in spawn_digits_child but for chars child process
}
void wait_until_children_finish(pid_t pid1, pid_t pid2) {
//use waitpid to wait for child process termination
}
void read_and_write(const char *digits_fifo, const char *chars_fifo) {
//read input string
//open the two named pipes with O_WRONLY
//check with isdigit respective isalpha and send to the corresponding named pipe
//don't forget to close file handles
}
void chars_child(const char *chars_fifo) {
//open named piped with O_RDONLY
//e.g. int chars_fd = open(chars_fifo, O_RDONLY);
//read from pipe
//do uppercase string
//output it with printf
}
void digits_child(const char *digits_fifo) {
//open named piped with O_RDONLY
//e.g. int chars_fd = open(digits_fifo, O_RDONLY);
//read from pipe
//output it with printf
}
I've implemented the beginning of a C shell as below. So far I have my redirection working, and I thought I would implement | in a similar way but am having difficulty.
Can anyone help?
I would begin with checking for the pipe operator, then saving the sa[i-1] and sa[i+1] as the two separate commands, but I'm not sure how to fork() and exec() properly after this.
int startProcess (StringArray sa)
{
int pid;
int status;
int fd1;
int fd2;
int current_in;
int current_out;
int fd0;
int fd00;
int in = 0;
int out = 0;
char input[64]="";
char output[64]="";
char cmd1[64] ="";
char cmd2[64] ="";
int fd[2];
int pipe = 0;
switch( pid = fork()){
case -1://This is an error
perror("Failure of child.");
return 1;
case 0: // This is the child
// Redirection
/* finds where '<' or '>' occurs and make that sa[i] = NULL ,
to ensure that command wont' read that*/
for(int i=0;sa[i]!='\0';i++)
{
if(strcmp(sa[i],"<")==0)
{
sa[i]=NULL;
strcpy(input,sa[i+1]);
in=2;
}
if(strcmp(sa[i],">")==0)
{
sa[i]=NULL;
strcpy(output,sa[i+1]);
out=2;
}
}
//if '<' char was found in string inputted by user
if(in)
{
// fdo is file-descriptor
int fd0;
if ((fd0 = open(input, O_RDONLY, 0)) < 0) {
perror("Couldn't open input file");
exit(0);
}
// dup2() copies content of fdo in input of preceeding file
dup2(fd0, 0); // STDIN_FILENO here can be replaced by 0
close(fd0); // necessary
}
//if '>' char was found in string inputted by user
if (out)
{
int fd00 ;
if ((fd00 = creat(output , 0644)) < 0) {
perror("Couldn't open the output file");
exit(0);
}
dup2(fd00, STDOUT_FILENO); // 1 here can be replaced by STDOUT_FILENO
close(fd00);
}
execvp(sa[0], sa);
perror("execvp");
_exit(1);
printf("Could not execute '%s'\n", sa[0]);
default:// This is the parent
wait(&status);
return (status == 0) ? 0: 1;
}
}
Make a pipe.
fork().
In the parent set the STDOUT file descriptor (1) to the input of your pipe.
In the child set the STDIN file descriptor (0) to the output of your pipe.
exec() in both the parent and the child.
Do all of this in the child after you fork(), just like for redirection.
I have been working on creating a pipe in c between two programs, reader.c and writer.c. I haven't been able to get the input for the pipe program to work. The pipe program is supposed to take in a int, send it to the writer program, which then pipes its output into the reader program for the final output. Below is the code for the three classes. I think I am close but can anyone help me get the initial int input argv[2] into the writer class then into the reader class?
pipe program (communicat.c)
int main(int argc, char *argv[])
{
int fd[2];
pid_t childpid;
int result;
if (argc != 2)
{
printf("usage: communicate count\n");
return -1;
}
pipe(fd);
childpid = fork();
if (childpid == -1)
{
printf("Error in fork; program terminated\n");
return -1;
}
if(childpid == 0)
{
close(1);
dup(fd[1]);
execlp("writer", "writer", fd[1],(char *) NULL);
}
else
{
childpid = fork();
}
if( childpid == 0)
{
close(0);
dup(fd[0]);
close(fd[0]);
close(fd[1]);
execlp("reader", "reader", (char *) NULL);
}
else
{
close(fd[0]);
close(fd[1]);
int status;
wait(&status);
}
return(0);
}
Reader.c
int main()
{
int count; /* number of characters in the line */
int c; /* input read */
count = 0;
while ((c = getchar())!= EOF)
{
putchar(c); count++;
if (count == LINELENGTH)
{
putchar('\n'); count = 0;
}
}
if (count > 0)
putchar('\n');
return 0;
}
Writer.c
int main(int argc, char *argv[])
{
int count; /* number of repetitions */
int i; /* loop control variable */
if (argc != 2)
{
printf("usage: writer count\n");
return -1;
}
else count = atoi(argv[1]);
for (i = 0; i < count; i++)
{
printf("Hello");
printf("hello");
}
return 0;
}
Correct the code to exec writer this way:
if(childpid == 0)
{
close(1);
dup(fd[1]);
close(fd[0]);
close(fd[1]);
execlp("writer", "writer", argv[1], (char *) NULL);
}
I have a problem with pipes. My program is a Shell program in C. I want to execute for example ls | wc, but what I get after running is:
ls: cannot access |: no such file or directory ls: cannot access wc: no such file or directory.
What am I doing wrong?
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#define MAX_CMD_LENGTH 100
#define MAX_NUM_PARAMS 10
int parsecmd(char* cmd, char** params) { //split cmd into array of params
int i,n=-1;
for(i=0; i<MAX_NUM_PARAMS; i++) {
params[i] = strsep(&cmd, " ");
n++;
if(params[i] == NULL) break;
}
return(n);
};
int executecmd(char** params) {
pid_t pid = fork(); //fork process
if (pid == -1) { //error
char *error = strerror(errno);
printf("error fork!!\n");
return 1;
} else if (pid == 0) { // child process
execvp(params[0], params); //exec cmd
char *error = strerror(errno);
printf("unknown command\n");
return 0;
} else { // parent process
int childstatus;
waitpid(pid, &childstatus, 0);
return 1;
}
};
int execpipe (char ** argv1, char ** argv2) {
int fds[2];
pipe(fds);
int i;
pid_t pid = fork();
for (i=0; i<2; i++) {
if (pid == -1) { //error
char *error = strerror(errno);
printf("error fork!!\n");
return 1;
} else
if (pid == 0) {
if(i ==0){
close(fds[1]);
dup2(fds[0], 0);
close(fds[0]);
execvp(argv1[0], argv1);
char *error = strerror(errno);
printf("unknown command\n");
return 0;
} else if(i == 1) {
close(fds[0]);
dup2(fds[1], 1);
close(fds[1]);
execvp(argv2[0], argv2);
char *error = strerror(errno);
printf("unknown command\n");
return 0;
}
} else { // parent process
int childstatus;
waitpid(pid, &childstatus, 0);
return 1;
}
} // end for
};
int main() {
char cmd[MAX_CMD_LENGTH+1];
char * params[MAX_NUM_PARAMS+1];
char * argv1[MAX_NUM_PARAMS+1];
char * argv2[MAX_NUM_PARAMS+1];
int k, y, x;
int f = 1;
while(1) {
printf("$"); //prompt
if(fgets(cmd, sizeof(cmd), stdin) == NULL) break; //read command, ctrl+D exit
if(cmd[strlen(cmd)-1] == '\n') { //remove newline char
cmd[strlen(cmd)-1] = '\0';
}
int j=parsecmd(cmd, params); //split cmd into array of params
if (strcmp(params[0], "exit") == 0) break; //exit
for (k=0; k <j; k++) { //elegxos gia uparksi pipes
if (strcmp(params[k], "|") == 0) {
f = 0; y = k;
printf("pipe found\n");
}
}
if (f==0) {
for (x=0; x<k; x++) {
argv1[x]=params[x];
}
int z = 0;
for (x=k+1; x< j; x++) {
argv2[z]=params[x];
z++;
}
if (execpipe(argv1, argv2) == 0) break;
} else if (f==1) {
if (executecmd(params) == 0) break;
}
} // end while
return 0;
}
Updated your code with following corrections.
Removed for() loop that iterated two times after fork() call.
Removed incorrect close of pipe FDs after dup2 calls for both parent and child processes.
Aligned the command that needed to be run as per the file descriptors that were duplicated in dup2() calls for parent and child. Basically I needed to swap execvp(argv2[0], argv2) and execvp(argv1[0], argv1) calls.
Added a break; statement in the for loop that searched for pipe character.
The updated code is as below.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
#define MAX_CMD_LENGTH 100
#define MAX_NUM_PARAMS 10
int parsecmd(char* cmd, char** params) { //split cmd into array of params
int i,n=-1;
for(i=0; i<MAX_NUM_PARAMS; i++) {
params[i] = strsep(&cmd, " ");
n++;
if(params[i] == NULL) break;
}
return(n);
};
int executecmd(char** params) {
pid_t pid = fork(); //fork process
if (pid == -1) { //error
char *error = strerror(errno);
printf("error fork!!\n");
return 1;
} else if (pid == 0) { // child process
execvp(params[0], params); //exec cmd
char *error = strerror(errno);
printf("unknown command\n");
return 0;
} else { // parent process
int childstatus;
waitpid(pid, &childstatus, 0);
return 1;
}
};
int execpipe (char ** argv1, char ** argv2) {
int fds[2];
pipe(fds);
int i;
pid_t pid = fork();
if (pid == -1) { //error
char *error = strerror(errno);
printf("error fork!!\n");
return 1;
}
if (pid == 0) { // child process
close(fds[1]);
dup2(fds[0], 0);
//close(fds[0]);
execvp(argv2[0], argv2); // run command AFTER pipe character in userinput
char *error = strerror(errno);
printf("unknown command\n");
return 0;
} else { // parent process
close(fds[0]);
dup2(fds[1], 1);
//close(fds[1]);
execvp(argv1[0], argv1); // run command BEFORE pipe character in userinput
char *error = strerror(errno);
printf("unknown command\n");
return 0;
}
};
int main() {
char cmd[MAX_CMD_LENGTH+1];
char * params[MAX_NUM_PARAMS+1];
char * argv1[MAX_NUM_PARAMS+1] = {0};
char * argv2[MAX_NUM_PARAMS+1] = {0};
int k, y, x;
int f = 1;
while(1) {
printf("$"); //prompt
if(fgets(cmd, sizeof(cmd), stdin) == NULL) break; //read command, ctrl+D exit
if(cmd[strlen(cmd)-1] == '\n') { //remove newline char
cmd[strlen(cmd)-1] = '\0';
}
int j=parsecmd(cmd, params); //split cmd into array of params
if (strcmp(params[0], "exit") == 0) break; //exit
for (k=0; k <j; k++) { //elegxos gia uparksi pipes
if (strcmp(params[k], "|") == 0) {
f = 0; y = k;
printf("pipe found\n");
break;
}
}
if (f==0) {
for (x=0; x<k; x++) {
argv1[x]=params[x];
}
int z = 0;
for (x=k+1; x< j; x++) {
argv2[z]=params[x];
z++;
}
if (execpipe(argv1, argv2) == 0) break;
} else if (f==1) {
if (executecmd(params) == 0) break;
}
} // end while
return 0;
}
If you are interested only in changes I made, here is the diff between your code and the above updated code:
--- original.c
+++ updated.c
## -4,6 +4,7 ##
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
+#include <sys/wait.h>
#define MAX_CMD_LENGTH 100
## -43,44 +44,36 ##
pipe(fds);
int i;
pid_t pid = fork();
- for (i=0; i<2; i++) {
if (pid == -1) { //error
char *error = strerror(errno);
printf("error fork!!\n");
return 1;
- } else
- if (pid == 0) {
- if(i ==0){
+ }
+ if (pid == 0) { // child process
close(fds[1]);
dup2(fds[0], 0);
- close(fds[0]);
- execvp(argv1[0], argv1);
+ //close(fds[0]);
+ execvp(argv2[0], argv2); // run command AFTER pipe character in userinput
char *error = strerror(errno);
printf("unknown command\n");
return 0;
- } else if(i == 1) {
+ } else { // parent process
close(fds[0]);
dup2(fds[1], 1);
- close(fds[1]);
- execvp(argv2[0], argv2);
+ //close(fds[1]);
+ execvp(argv1[0], argv1); // run command BEFORE pipe character in userinput
char *error = strerror(errno);
printf("unknown command\n");
return 0;
}
- } else { // parent process
- int childstatus;
- waitpid(pid, &childstatus, 0);
- return 1;
- }
- } // end for
};
int main() {
char cmd[MAX_CMD_LENGTH+1];
char * params[MAX_NUM_PARAMS+1];
- char * argv1[MAX_NUM_PARAMS+1];
- char * argv2[MAX_NUM_PARAMS+1];
+ char * argv1[MAX_NUM_PARAMS+1] = {0};
+ char * argv2[MAX_NUM_PARAMS+1] = {0};
int k, y, x;
int f = 1;
while(1) {
## -95,6 +88,7 ##
if (strcmp(params[k], "|") == 0) {
f = 0; y = k;
printf("pipe found\n");
+ break;
}
}
if (f==0) {
execv* procedure doesn't interpret shell script string. It merely starts an executable file and passes an array of arguments to it. Thus, it cannot organize a pipeline.
If you need "normal" shell command execution, you may want to use system(char*) procedure instead of execvp.
Otherwise, if you need to do the pipes yourself, you may want to parse the string with '|' special characters and use pipe(), fork() and I/O redirection. Like here How to run a command using pipe?
I am writing a c program involving communication between child and parent by directional pipe
Here is part of my code:
char writemsg[BUFFER_SIZE] = "Sugar Lover";
char readmsg[BUFFER_SIZE];
char parrecieve[BUFFER_SIZE];
char childrecieve[BUFFER_SIZE+1];
int fd[2];
int fd2[2];
pid_t pid;
if (pipe(fd) == -1|| pipe(fd2) == -1) {
printf("Pipe failed");
return 1;
}
pid = fork();
if (pid < 0) { /* error occurred */
printf( "Fork Failed");
return 1;
}
if (pid > 0) { /* parent process */
int i =0;
close(fd[READ_END]);/* close the unused end of the pipe */
while(writemsg[i] !='\0'){
write(fd[WRITE_END],&writemsg[i] , sizeof(char));
i++;
}
close(fd[WRITE_END]);
i = 0;
close(fd2[WRTIE_END]);
while(read(fd2[READ_END], &parrecieve[i], sizeof(char))!=0){
printf("%c", parrecieve[i]);
i++;
}
close(fd2[READ_END]);
}
It's complaining about this line when compiling:
close(fd2[WRTIE_END]);
Could anybody tell me why?Thanks!
Just rename WRTIE_END to WRITE_END.
Read error messages more carefully and try to understand them.