I wrote a program to use ls command in Linux terminal to read the content of the folder and write the text from ls to the screen with my C program. Here's the code I wrote:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{
int pipe_ends[2];
if(pipe(pipe_ends))
{
printf("Could not create pipe\n");
return -1;
}
pid_t pid = fork();
if(pid < 0)
{
perror("fork");
exit(1);
}
if(!pid)
{
dup2(pipe_ends[0],1);
char* args[3];
args[0] = "/bin/ls";
args[1] = "-l";
args[2] = NULL;
execv("/bin/ls",args);
printf("something went wrong\n");
}
char buff[10240];
int count = read(pipe_ends[1],buff,10240);
buff[count] = '\0';
printf("here goes nothing......\n");
printf("%s",buff);
return 0;
}
The output I get for this program is:
here goes nothing......
od@od-Inspiron-N5110:~/Documents/work/new/CO/project1$ /bin/ls: write error: Bad file descriptor
od@od-Inspiron-N5110:~/Documents/work/new/CO/project1$
It seems that reading has been done before writing. But I thought read is blocking. Please help me to find the error here.
Thanks in advance.