FIFO pipe - Child wont read properly - c

I try to use two FIFOs, one for the child process and one for the parent.
First, the child should write a question in the parent FIFO.
Parent waits until question arrives, then reads it, answers it and writes the answer in the child's FIFO.
Child waits for the answer, then reads it and puts it out.
Problem is, somehow the child reads always an empty answer and I don't know why.
Code below:
MAIN:
int main() {
pid_t child, parent;
char quest[PIPE_BUF];
int n=0;
switch(fork()) {
case CHILD: {
while(n==0){
printf("Bitte Frage stellen\n");
n=scanf("%s", quest);
}
}
child = getpid();
question(quest, child);
break;
case ERROR:
perror("fork():");
break;
default:
printf("waiting for input\n");
parent = getpid();
oracle(parent);
}
return EXIT_SUCCESS;
}
CHILD FUNCTION
void question(const char *buf, pid_t pid ){
char filename[PIPE_BUF];
if (mkfifo(ANSW, 0666) == -1){
if(errno == EEXIST)
perror(" oracle mkfifo:");
else{
perror(" oracle mkfifo:");
exit(EXIT_FAILURE);
}
}
int fd, fd2;
fd = open(FIFO, O_WRONLY);
char quest[PIPE_BUF + 1];
char answer[PIPE_BUF + 1];
int n = 0;
sprintf(quest, "%d:", pid);
strcat(quest,buf);
write(fd,quest,strlen(quest));
sleep(2);
fd2= open(ANSW,O_RDONLY);
printf("%s\n", answer);
while(1) {
n=read(fd2, answer, strlen(answer));
if (n == -1) {
perror(" client read():");
break;
} else if (n > 0){
puts(answer);
break;
}
}
remove("/tmp/answer.me");
unlink(FIFO);
unlink(ANSW);
close(fd);
close(fd2);
}
PARENT FUNCTIONS:
int isVokal(const char* buf, int i){
if (buf[i] == '?' && ((buf[i-1] == 'a') || (buf[i-1] == 'e') ||(buf[i-1] == 'i') || (buf[i-1] == 'o') || (buf[i-1] == 'u')))
return 1;
else
return 0;
}
int answer(char * buf, pid_t pid){
int i = 0;
int fd = open(ANSW, O_WRONLY);
char answer[PIPE_BUF + 1];
size_t x = strlen(buf);
buf[x+1] = '\0';
do{
i++;
if(buf[i] == '\0'){
--i;
if(buf[i] != '?'){
sprintf(answer, "%s","Dies ist keine Frage.\n");
write(fd,answer, strlen(answer));
i++;
}else if(isVokal(buf,i)){
sprintf(answer, "%s","Yes!\n");
write(fd,answer, strlen(answer));
i++;
}else{
sprintf(answer, "%s","No!\n");
write(fd,answer, strlen(answer));
i++;
}
}
}while ( buf[i] != '\0');
close(fd);
return 0;
}
void oracle(pid_t pid) {
int i = 1;
if ((mkfifo(FIFO, 0666) == -1)){
if(errno == EEXIST)
perror(" oracle mkfifo:");
else{
perror(" oracle mkfifo:");
exit(EXIT_FAILURE);
}
}
int fd = open(FIFO, O_RDONLY);
if(fd == -1)
perror(" oracle open():");
char buf[PIPE_BUF + 1];
while (i) {
printf("waiting for input\n");
int n = read(fd, buf, PIPE_BUF);
if (n == -1)
perror(" oracle read():");
else if (n >= 0)
i=answer(buf, pid);
}
close(fd);
remove("/tmp/ask.me");
unlink(FIFO);
unlink(ANSW);
}

Related

Pass parameter to another function using C

int main(void){
int n, user_length;
char userid[30];
char password[11];
if ((n = read(STDIN_FILENO, userid, 10)) == -1) {
perror("read");
exit(1);
} else if(n == 0) {
fprintf(stderr, "Error: could not read from stdin");
exit(1);
}
if (userid[n-1] == '\n')
userid[n-1] = '\0';
else
userid[n] = '\0';
if ((n = read(STDIN_FILENO, password, 10)) == -1) {
perror("read");
exit(1);
} else if (n == 0) {
fprintf(stderr, "Error: could not read from stdin");
exit(1);
}
if (password[n-1] == '\n')
password[n-1] = '\0';
else
password[n] = '\0';
strcat(userid, ":");
user_length = strlen(userid);
strcat(userid, password);
FILE *fp = fopen(PASSWORD_FILE, "r");
if (!fp) {
perror("fopen");
exit(1);
}
char line[MAXLINE];
while(fgets(line, sizeof(line) - 1, fp)) {
line[strlen(line) - 1] = '\0';
if (strcmp(userid, line) == 0)
exit(0); // found match
else if(strncmp(userid, line, user_length) == 0)
exit (2); // invalid password
}
exit(3); // no such user
}
Above is the implementation of validate.c, but how do I pass value such as userid and password to the function by using pipe(),dup2 or execl()
I used the following`
int main(void) {
char userid[10];
char password[10];
int pid;
int p[2][4];
char other[MAXSIZE];
/* Read a user id and password from stdin */
printf("User id:\n");
scanf("%s", userid);
printf("Password:\n");
scanf("%s", password);
/*Your code here*/
if (pipe(p[1]) == -1) {
perror("pipe");
}
if (pipe(p[0]) == -1) {
perror("pipe");
}
pid = fork();
if (pid != 0) {
close(p[1][0]);
close(p[0][0]);
dup2(p[1][1],STDIN_FILENO);
dup2(p[0][1],STDIN_FILENO);
close(p[1][1]);
close(p[0][1]);
int status;
if (wait(&status)!= -1) {
if (WIFEXITED(status)) {
printf("[%d] Child exited with %d\n", getpid(), WEXITSTATUS(status));
switch(WEXITSTATUS(status)){
case 0:
printf("found match\n");
break;
case 2:
printf("invalid password\n");
break;
case 3:
printf("No such user\n");
break;
default:
printf("error has occur\n");
break;
};
} else {
printf("[%d] Child exited abnormally\n", getpid());
}
}
} else if (pid == 0) {
close(p[1][1]);
close(p[0][1]);
dup2(p[1][0], fileno(stdout));
dup2(p[1][0], fileno(stdout));
execl("validate",other);
printf("what\n");
close(p[1][0]);
close(p[0][0]);
} else {
perror("fork");
exit(1);
}
return 0;
}
But the prompt always asks me for re-entering the input. What is wrong with this approach?( Note: I "execl" "validate" because it is an executable file that has been already created. The execl() I wrote simply calls the validate.c function )
As I said in the comments you probably do not need to spawn another process for this but You have an error in the way you call execl.
This:
execl("validate",other);
Should be:
execl(filename,list of arguments, NULL);
This is the documentation page. They use (char *) 0 which is the same as using NULL.

Shell program with pipes in C

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?

Piping in C - Error in Command 2

So, I thought I was on the right track with trying to imitate the bash shell, but I'm having issues piping. I am getting an error executing the second command. I was wondering if someone could explain to me how to fix this and why it's going wrong.
I'm very new to C & Linux commands so any supplemental information that could help me along the way would be also be appreciated.
Thank you so much for your time. My code is below, but there is a lot of it. My issue is occurring in the exec_pipe function. I would normally include what I have used for input and what I am getting for output, but my sample input is actually executable files my professor gave us for testing. Unfortunately, mine is not working like it does in the shell. I am just getting my error print out:
Inside Case 5
Inside Exec_Pipe
Error in Pipe EXECVP cmd2
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdbool.h>
#include <time.h>
#include <limits.h>
#include <fcntl.h>
#include <sys/wait.h>
#define BUFSIZE 1024
#define CSTRSIZE 100
#define CMDSIZE 30
#define DEBUG 1
//I referenced our blackboard source code files to create the fork functions and to deal with file descriptors
void exec_cmd(char** cmd1){
pid_t pid;
if((pid = fork()) < 0){
printf("Child Process Failed\n");
}else if(pid == 0){
if(execvp(cmd1[0], cmd1) < 0){
printf("Execution Failed\n");
exit(1);
}
}else{
wait(NULL);
}
}
void exec_cmd_in(char** cmd1, char* infile){
pid_t pid;
int fdi;
if((pid = fork()) < 0){
printf("Child Process Failed\n");
}else if(pid == 0){
fdi = open(infile, O_RDONLY);
if(fdi == -1){
printf("No Infile");
}
}
}
void exec_cmd_opt_in_append(char** cmd1, char* infile, char* outfile){
/* pid_t pid;
int fdi, fdo;
if((pid = fork()) < 0){
printf("Child Process Failed\n");
}else if(pid == 0){
fdo = open(outfile, O_RDWR | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR);
if(fdo == -1){
printf("No Outfile");
}
if(dup2(fdi, 0) == -1){
printf("Infile not updated");
}
if(dup2(fdo, 1) == -1){
printf("Outfile not updated");
}
close(fdi);
close(fdo);
if(execvp(cmd1[0], cmd1) < 0){
printf("Execution Failed\n");
exit(1);
}
}else{
wait(NULL);
} */
}
void exec_cmd_opt_in_write(char** cmd1, char* infile, char* outfile){
/* pid_t pid;
int fdi, fdo;
if((pid = fork()) < 0 ){
printf("Fork Error");
exit(1);
}else if(pid == 0 ){
fdo = open(outfile, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
if(fdo == -1){
printf("No Outfile");
}
if(dup2(fdi, 0) == -1){
printf("Infile not updated");
}
if(dup2(fdo, 1) == -1){
printf("Outfile not updated");
}
close(fdi);
close(fdo);
if(execvp(cmd1[0], cmd1) < 0){
printf("Execution Failed\n");
exit(1);
}
}else{
wait(NULL);
}
*/
}
void exec_pipe(char** cmd1, char** cmd2){
pid_t pid;
int pipefd[2];
// pipe[1] is the write end of the pipe
// pipe[0] is the read end of the pipe
// making a pipe
printf("Inside Exec_Pipe\n");
pid = fork();
switch(pid){
case -1:
//error in fork
printf("Fork Error\n");
//Exit
exit(1);
case 0:
//child
break;
default:
//parent
wait(NULL);
}
//This will be executed by child process
if(pipe(pipefd) < 0 ) {
//error condition
printf("Pipe Error");
exit(1);
}
pid = fork();
switch(pid){
case -1:
//error in fork
printf("Fork Error\n");
//Exit
case 0:
//child
close(STDIN_FILENO);
//direct STDOUT to the pipe
dup2(pipefd[1], STDOUT_FILENO);
//Close descriptors
close(pipefd[0]);
close(pipefd[1]);
//Execute Command1
execvp(cmd1[0], cmd1);
//execvp should not return, so if it does
//there is an error!
printf("Error in EXECVP cmd1");
exit(1);
default:
//parent
close(STDIN_FILENO);
//direct input to the pipe
dup2(pipefd[0],STDIN_FILENO);
//close descriptors
close(pipefd[0]);
close(pipefd[1]);
//execute command 2
execvp(cmd2[0],cmd2);
//if execvp makes it back, error condition
printf("Error in Pipe EXECVP cmd2");
exit(1);
}
}
void exec_pipe_opt_in_append(char** cmd1, char** cmd2, char* infile, char* outfile){
}
void exec_pipe_opt_in_write(char** cmd1, char** cmd2, char* infile, char* outfile){
}
int parse_command(char* line, char** cmd1, char** cmd2, char* infile, char* outfile){
/*
(1)Create a bunch of flags to compare for the right return value
(2)Loop over the entire line and set the flags
(3)Add a bunch of if statements to compare flags
(4)If there is more than one flag for pipe, we can't handle it. Regurn 9.
(5)If there is &, we can't handle.
(6)Return the right value
*/
int pipe_found = 0;
int input_found = 0;
int redirection = 0;
int i = 0;
int spaces = 0;
int append = 0;
int special = 0;
while(line[i] != '\0'){
if(line[i] == '|'){
pipe_found++;
}
if(line[i] == '<'){
input_found = 1;
}
if((line[i] == '&') || (line[i] == '*') || (line[i] == '^') || (line[i] == '%') || (line[i] == '#') || (line[i] == '!') || (line[i] == '#') || (line[i] == '(') || (line[i] == ')')){
special = 1;
}
if(line[i] == '>'){
redirection = 1;
if(line[i+1] == '>'){
append = 1;
}
}
if(line[i] == ' '){
spaces++;
}
i++;
}
if((strlen(line) >=4) && (line[0] == 'q') && (line[1] == 'u') && (line[2] == 'i') && (line[3] == 't')){
return 0;
}
if((pipe_found == 0) && (special == 0)){
if((redirection == 0) && (input_found == 0)){
return 1;
}else if((redirection == 0) && (input_found == 1)){
return 2;
}else if(append == 1){
return 3;
}else if(redirection == 1){
return 4;
}
}else if((pipe_found == 1) && (special == 0)){
if((redirection == 0) && (input_found == 0)){
return 5;
}else if((redirection == 0) && (input_found == 1)){
return 6;
}else if(append == 1){
return 7;
}else if(redirection == 1){
return 8;
}
}
return 9;
}
//I referenced StackOverflow and some online libraries to get this tokenize function
char ** tokenize(char *str, char *delim, unsigned int *number_tokens) {
char *pch = strtok(str, delim);
unsigned int ntok = 0;
if(pch != NULL) {
ntok = 1;
}else{
return NULL;
}
char **tokens = realloc(NULL, sizeof(char *)*ntok);
tokens[ntok-1] = pch;
while(pch != NULL) {
pch = strtok(NULL, delim);
ntok++;
tokens = realloc(tokens, sizeof(char *)*ntok);
tokens[ntok-1] = pch;
}
if(number_tokens) {
*number_tokens = ntok;
}
return tokens;
}
//I referenced StackOverflow.com for this trim function
char *trim(char *str) {
char *end;
if(str == NULL){
return NULL;
}
while(isspace(*str)){
str++;
}
end = str + strlen(str) - 1;
while(end > str && isspace(*end)) {
end--;
}
*(end+1) = 0;
return str;
}
int main(int argc, char *argv[]){
int returnValue = 0;
char *infile = NULL;
char *outfile = NULL;
char **cmd = NULL;
char **cmd1_tokens = NULL;
char **cmd2_tokens = NULL;
char *input;
int current_cmd = 0;
/*
(1)If the user does not enter a command line argument, get one after typing "myshell-%"
(2)Call parse_command on the user input to get the right return value
(3)Begin parsing the user input within main
*/
if(argc == 1){
printf("myshell-%%\n");
fgets (input, 20, stdin);
returnValue = parse_command(input, cmd1_tokens, cmd2_tokens, infile, outfile);
cmd = tokenize(input, "|", NULL);
}else{
returnValue = parse_command(argv[1], cmd1_tokens, cmd2_tokens, infile, outfile);
cmd = tokenize(argv[1], "|", NULL);
}
int infileIt = 0;
while(cmd[current_cmd] != NULL) {
unsigned int number_tokens = 0;
char **infile_token = tokenize(cmd[current_cmd], "<", &number_tokens);
if(number_tokens > 1){
while(infile_token[infileIt] != NULL){
infileIt++;
}
}
if(infile_token[1] != NULL) {
number_tokens = 0;
char **infile_outfile_token = tokenize(infile_token[1], ">", &number_tokens);
if(number_tokens > 1){
infile = infile_outfile_token[0];
infile = infile_token[1];
}
}
number_tokens = 0;
char **outfile_token = tokenize(cmd[current_cmd], ">", &number_tokens);
if(number_tokens > 1){
outfile = outfile_token[1];
}
current_cmd++;
}
//Trim the in/outfiles
infile = trim(infile);
outfile = trim(outfile);
/*
Start breaking up cmd[0] and cmd[1] into smaller chunks and saving into the appropriate cmd
*/
cmd1_tokens = tokenize(cmd[0], " ", NULL);
if(cmd[1] != NULL){
cmd2_tokens = tokenize(cmd[1], " ", NULL);
}
int cmd1Args = 0;
while(cmd1_tokens[cmd1Args] != NULL){
cmd1Args++;
}
int cmd2Args= 0;
if(cmd2_tokens != NULL){
while(cmd2_tokens[cmd2Args] != NULL){
cmd2Args++;
}
}
int iterator = 0;
while((iterator < cmd1Args) && (cmd1Args != 0)){
printf("Cmd1: %s\n", cmd1_tokens[iterator]);
iterator++;
}
iterator = 0;
while((iterator < cmd2Args)&&(cmd2Args != 0)){
printf("Cmd2: %s\n", cmd2_tokens[iterator]);
iterator++;
}
if(infile != NULL){
printf("Infile: %s\n", infile);
}
if(outfile != NULL){
printf("Outfile: %s\n", outfile);
}
/*Use a switch statement to process all the return values (0 ot 9) of parse_command.
Our program should execute the “line” if the return code from parse_command
function is 0 to 8, that is the line is deemed “valid”. For return code 9,
our program simply output ”Not handled at this time!”.*/
switch(returnValue){
case 0 :
printf("Exiting Program.\n");
exit(1);
break;
case 1 :
printf("Inside Case 1\n");
exec_cmd(cmd1_tokens);
break;
case 2 :
printf("Inside Case 2\n");
exec_cmd_in(cmd1_tokens, infile);
break;
case 3 :
printf("Inside Case 3\n");
exec_cmd_opt_in_append(cmd1_tokens, infile, outfile);
break;
case 4 :
printf("Inside Case 4\n");
exec_cmd_opt_in_write(cmd1_tokens, infile, outfile);
break;
case 5 :
printf("Inside Case 5\n");
exec_pipe(cmd1_tokens, cmd2_tokens);
break;
case 6 :
printf("Inside Case 6\n");
//exec_pipe_in(cmd1_tokens, cmd2_tokens, infile);
break;
case 7 :
printf("Inside Case 7\n");
exec_pipe_opt_in_append(cmd1_tokens, cmd2_tokens, infile, outfile);
break;
case 8 :
printf("Inside Case 8\n");
exec_pipe_opt_in_write(cmd1_tokens, cmd2_tokens, infile, outfile);
break;
default :
printf("Inside Case 9\n");
printf("Not handled at this time!\n");
}
return 0;
}
Without having access to the input file that you're giving it, it's a little hard to say what's going on, but here are some tips for debugging it.
First, when something you don't understand is happening, it can be a good idea to strip it down to a minimal, working, self contained example that demonstrates the problem. Sometimes, just the process of cutting it down to that small example can help you to find the problem; but if not, it gives you a much smaller example to ask about.
Next, when putting in these print statements to debug what's going on, give yourself a little more context. Especially in the one that indicates an error; print out what the error is, and what the arguments were to the function that failed. Rather than just:
printf("Error in Pipe EXECVP cmd2");
You can use strerror to get a string representing the error number:
printf("Error %d in Pipe EXECVP cmd2: %s\n", errno, strerror(errno));
And you can also print out what the command and all of your arguments were:
for (char **arg = cmd2; *arg != NULL; ++arg) {
printf("cmd2[%ld] = %s", arg - cmd2, *arg);
}
Between printing out the actual error and printing out the command name and all of the arguments, that should help you to debug the problem.
If you could add that information to your question, and maybe cut your example down to a more minimal example as well as showing a minimal example of the input that causes a problem, we could probably help out a lot more.

Pipes not working while implementing a minishell

I'm actually trying to implement a basic minishell in C. For doing that, I made a fonction which parse what the user enter in the console. I parsed it and then I would like to send the command to the console using pipes. I don't understand why my pipes are not working.
I checked the parsing and it seems to be fine, i have the right commands in parameters of the fonction.
The thing is that my pipe code is literally doing nothing and I don't understand why.
Here is my code.
Thank you in advance.
#define READ 0
#define WRITE 1
char *cmds[5] = {0};
int main() {
char *saisie = (char*)malloc(100*sizeof(char*));
char *saisie2 = (char*)malloc(100*sizeof(char*));
gets(saisie);
int ncmds = 0;
int k = 0;
char* token = (char*)malloc(100*sizeof(char*));
char* tofree;
if(*(saisie + 0) == '$'){
if(*(saisie + 2) == 'e' && *(saisie + 3) == 'x' && *(saisie + 4) == 'i' || *(saisie + 5) == 't'){
exit(0);
}
else{
int i;
for(i = 0;i<99;i++){
*(saisie2+i) = *(saisie+i+1);
}
free(saisie);
if (saisie2 != NULL) {
tofree = saisie2;
while ((token = strsep(&saisie2, "|")) != NULL){
cmds[ncmds] = token;
ncmds++;
}
free(tofree);
}
}
}
exe(cmds, ncmds);
while(wait(NULL) > 0);
return 0;
}
int exe(char *cmds[], int ncmds){
int fdin, fdout;
int fds[2];
int i;
int status;
fdin = 0;
for(i=0; i < ncmds-1; i++){
pipe(fds);
fdout = fds[WRITE];
if(fork() == 0){
if( fdin != 0 ) {
close(0);
dup(fdin);
close(fdin);
}
if( fdout != 1 ) {
close(1);
dup(fdout);
close(fdout);
}
close(fds[READ]);
const char* prog2[] = {cmds[i], "-l", 0};
execvp(cmds[i], prog2);
fprintf(stderr, "si esto se ve es un error\n");
exit(1);
}
if(fdin != 0)
close(fdin);
if(fdout != 1)
close(fdout);
fdin = fds[READ];
}
/* Ultimo comando */
fdout = 1;
if(fork() == 0) {
if( fdin != 0 ) {
close(0);
dup(fdin);
close(fdin);
}
const char* prog2[] = {cmds[i], "-l", 0};
execvp(cmds[i], prog2);
close(fds[READ]);
exit(1);
}
if(fdout!= 1)
close(fdout);
if(fdin != 0)
close(fdin);
}
}
int exe(char *cmds[], int ncmds){
int p2c[2];//pipe parent to child
int c2p[2];//pipe child to parent
int i;
int status;
int pid;
char buf[4096];
memset(buf, 0, 4096);
for(i=0; i < ncmds; i++){
pipe(p2c);
pipe(c2p);
pid = fork();
if(pid < 0) {
exit 1;
}
if(pid == 0){ //in child
close(1);
dup2(c2p[1],1); // make child write to c2p pipe instead of stdout
close(0);
dup2(p2c[0],0); // make child read from p2c pipe instead of stdin
close(p2c[1]);
close(c2p[0]);
const char* prog2[] = {cmds[i], "-l", 0};
execvp(cmds[i], prog2);
fprintf(stderr, "si esto se ve es un error\n");
exit(1);
}
//in parent
write(p2c[1], buf, strlen(buf)); //write the last output to child
close(p2c[1]);
close(c2p[1]);
memset(buf,0,4096);
if(read(c2p[0], buf, 4096) > 0){ //read output from child
if(i == ncmds -1 ){
printf("result:\n");
printf("%s\n", buf);
}
}
}
}

Multiple children reading from/writing to a single parent

Here I have a program where a parent process creates several child processes, passes
a distinct integer to each of them. Then each child process writes back the integer read to the parent process, which prints the result to standard output:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#define R 0
#define W 1
void run_child(int in, int out){
int r;
int it;
while((r = read(in, &it, sizeof(it))) != 0){
if(r == -1){
perror("read");
exit(1);
}
//word[r] = '\0';
int w = write(out, &it, sizeof(it));
if(w == -1){
perror("write");
exit(1);
}
if(close(out) == -1){
perror("close");
exit(1);
}
}
}
int main(int argc, char **argv) {
// Process fan
int i;
int n;
int num_kids;
int from_parent[2];
int to_parent[2];
if(argc != 2) {
fprintf(stderr, "Usage: fan_write <numkids>\n");
exit(1);
}
num_kids = atoi(argv[1]);
int status;
char word[32];
for(i = 0; i < num_kids; i++) {
if(pipe(from_parent) == -1){
perror("pipe");
exit(1);
}
if(pipe(to_parent) == -1){
perror("pipe");
exit(1);
}
int g = i;
write(from_parent[W], &g, sizeof(int));
n = fork();
if(n < 0) {
perror("fork");
exit(1);
}
if(n == 0){
if(close(from_parent[W]) == -1){
perror("close");
exit(1);
}
if(close(to_parent[R]) == -1){
perror("close");
exit(1);
}
dup2(from_parent[R], STDIN_FILENO);
if(close(from_parent[R]) == -1){
perror("close");
exit(1);
}
run_child(STDIN_FILENO, to_parent[W]);
close(to_parent[W]);
exit(0);
}
if(close(from_parent[R]) == -1){
perror("close");
exit(1);
}
if(close(to_parent[W]) == -1){
perror("close");
exit(1);
}
if(close(from_parent[W]) == -1){
perror("close");
exit(1);
}
for(i=0;i<num_kids;i++){
int read_int;
int r = read(to_parent[R], &read_int, sizeof(int));
printf("read %d bytes\n", r);
if(r == -1){
perror("read");
exit(1);
}
printf("%d\n", read_int);
}
}
for(i = 0; i < num_kids; i++){
wait(&status);
}
return 0;
}
With num_kids = 4 I would expect the program to read 4 bytes each time and print the
distinct integer. However, when run it reads 4 bytes in one iteration, and then it reads
0 bytes on the following iterations, and prints the same integer over and over. I'm not sure how to fix it.
Edit: Solved! Hint: use a matrix of file descriptors for pipes.
you have wrong concept to read numbers from all num_kids child process in a loop, your are reading every time from single child and in each child, by loop:
for(i=0;i<num_kids;i++){
int read_int;
int r = read(to_parent[R], &read_int, sizeof(int));
printf("read %d bytes\n", r);
if(r == -1){
perror("read");
exit(1);
}
printf("%d\n", read_int);
}
Is code runs for each child including parent too because you are unconditionally running this loop in child/parent process. But parent can read from single child that the reason you fist time get 4 byte then 0. because child return a number one time. Remove above for loop from your code and do like I am suggesting below:
you should do like(read comments):
if(n == 0){
//child
}
else{
// read in parent without loop
}
So correct way is:
if(n == 0){//child
if(close(from_parent[W]) == -1){
perror("close");
exit(1);
}
if(close(to_parent[R]) == -1){
perror("close");
exit(1);
}
dup2(from_parent[R], STDIN_FILENO);
if(close(from_parent[R]) == -1){
perror("close");
exit(1);
}
run_child(STDIN_FILENO, to_parent[W]);
close(to_parent[W]);
exit(0);
}
else{ // parent
write(from_parent[W], &g, sizeof(int));
int read_int;
int r = read(to_parent[R], &read_int, sizeof(int));
printf("read %d bytes\n", r);
if(r == -1){
perror("read");
exit(1);
}
printf("%d\n", read_int);
}
And its working like:
:~$ ./a.out 4
read 4 bytes
0
read 4 bytes
1
read 4 bytes
2
read 4 bytes
3
if (n == 0) { //child
if(close(from_parent[W]) == -1) {
perror("close");
exit(1);
}
if(close(to_parent[R]) == -1) {
perror("close");
exit(1);
}
run_child(from_parent[R], to_parent[W]);
close(from_parent[R]); // ignore checking return code here!
close(to_parent[W]); // ignore checking return code here!
exit(0);
}
// And this is what run_child looks like
void run_child(int in, int out){
int r;
int it;
while((r = read(in, &it, sizeof(it))) != 0){
if(r == -1){
perror("read");
exit(1);
}
int w = write(out, &it, sizeof(it));
if(w == -1){
perror("write");
exit(1);
}
}
}
I've mixed up the aswers code and this is the final result..
All succesful
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#define R 0
#define W 1
void run_child(int in, int out){
int r;
int it;
while((r = read(in, &it, sizeof(it))) != 0){
if(r == -1){
perror("read");
exit(1);
}
int w = write(out, &it, sizeof(it));
//perror("write:");
//close(out) ;
exit(1);
}
}
int main(int argc, char **argv) {
// Process fan
int i;
int n;
int num_kids;
int from_parent[2];
int to_parent[2];
if(argc != 2) {
fprintf(stderr, "Usage: fan_write <numkids>\n");
exit(1);
}
num_kids = atoi(argv[1]);
int status;
char word[32];
for(i = 0; i < num_kids; i++) {
if(pipe(from_parent) == -1){
perror("pipe");
exit(1);
}
if(pipe(to_parent) == -1){
perror("pipe");
exit(1);
}
int g = i;
write(from_parent[W], &g, sizeof(int));
n = fork();
if(n < 0) {
perror("fork");
exit(1);
}
if(n == 0){//child
if(close(from_parent[W]) == -1){
perror("close");
exit(1);
}
if(close(to_parent[R]) == -1){
perror("close");
exit(1);
}
run_child(from_parent[R], to_parent[W]);
if(close(from_parent[R]) == -1){
perror("close");
exit(1);
}
if(close(to_parent[W]) == -1){
perror("close");
exit(1);
}
exit(0);
}
else{ // parent
write(from_parent[W], &g, sizeof(int));
int read_int;
int r = read(to_parent[R], &read_int, sizeof(int));
printf("read %d bytes\n", r);
if(r == -1){
perror("read");
exit(1);
}
printf("%d\n", read_int);
}
}
for(i = 0; i < num_kids; i++){
wait(&status);
}
return 0;
}

Resources