2

I'm just starting to learn C programming and I have some uncertainty about fork(), exec(), pipe(), etc.

I've developed this code, but when I execute it, the variable c remains empty, so I don't know if the child isn't writing to the pipe, or the parent isn't reading from it.

Could you help me please? This is the code:

int main() { int pid=0; int pipefd[2]; char* c=(char *)malloc(sizeof(char)); FILE *fp; pipe(pipefd); pid=fork(); if (pid==0){ close(pipefd[0]); dup2(pipefd[1],1); close(pipefd[1]); execl("ls -l | cut -c28","ls -l | cut -c28", (char *) 0); } else{ close(pipefd[1]); read(pipefd[0], c, 1); char* path="/home/random"; char* txt=".txt"; char* root=malloc(strlen(path) + strlen(txt) + sizeof(char)); strcpy(root,path); strcat(root,c); strcat(root,txt); close(pipefd[0]); fp=fopen(root,"w+"); (...) } 

The problem is that the final root string its only "/home/random.txt" because there is nothing in the char c, and what I want is to open the file "/home/random(number stored in char c).txt".

1
  • Check that your execl call isn't returning - I don't think you can call execl like that. Commented Sep 21, 2012 at 15:32

3 Answers 3

1

execl executes a single command, and is not aware of shell concepts such as pipes. If you want to execute a shell command, you will have to execute a shell, as follows:

execl("/bin/sh","/bin/sh","-c","ls -l | cut -c28", (char*) 0); 
Sign up to request clarification or add additional context in comments.

2 Comments

Might be worth mentioning the NULL argv[0] - I don't think that's allowed either.
He did pass an argv[0], the same as the program name.
1

Always check the return value of the system calls (like execve(2) and derived functions like execl(3)), and use the errno(3) to figure out what went wrong.

In your case the execl line fails.

Comments

0

Using strcpy/strcat seems a bit excessively complex. snprintf can turn those 3 lines into one.

snprintf( root, size_of_buf, "/home/random%s", c ); 

Additionally, check your error codes. As noted, execl is failing and you don't know it. fork, dup2, ...,can also fail, you want to know sooner rather than later.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.