Take the 2-minute tour ×

user input is wc -c < filename my code is:

    dup2( fd, 0 );
    close( fd );
    if (fd < 0)
            perror("File open failed");
            return -1;
    if (fork() == 0)
            execvp(command, args,NULL);

But I have error "bad file descriptor"! how can I fix it?

share|improve this question
Are you saying that the variable command contains "wc -c < filename"? –  HeatfanJohn Aug 4 '12 at 22:05
no command contains only wc –  sweet Aug 4 '12 at 22:06
Also, what are you trying to do? dup2() duplicates a file descriptor, but you don't do anything with the file descriptor that it returns? For example, one would normally code anotherFD = dup2( fd ); –  HeatfanJohn Aug 4 '12 at 22:10
I want to read the "filename" and count number of characters in it show the result in command line. –  sweet Aug 4 '12 at 22:14
Then what's the purpose of calling dup2()? Also, according to the man page I just read for dup2(), the second parameter is suppose to be the file descriptor that fildes is duplicated onto. You are passing 0 which is not valid. –  HeatfanJohn Aug 4 '12 at 22:49
add comment

closed as too localized by Greg Hewgill, Kev Aug 5 '12 at 13:44


2 Answers

Check if fd < 0 before calling dup2.

share|improve this answer
No difference! I have same error –  sweet Aug 4 '12 at 22:10
None the less, it's a bug in the program as listed. Consider: what would your program do if there was a typo in filename? –  phs Aug 4 '12 at 22:12
add comment

problem solved I had close(1) at the start of my program. after removing that I got the result.

share|improve this answer
add comment
