1

Im implementing a shell in c, and im having a hard time redirecting the output of a command to a file. When i send the output to a file, it seems to work but the file does not open and when i run a ls -l it shows me the following:

---------x   1 warp  staff   441 Nov  4 20:15 output.txt

This is some part of my code

pid = fork();
if(pid == 0) 
{ /* child process */

    if(redirFlag)
    {
        int fdRedir = open(redirectName, O_WRONLY | O_CREAT );
        if( fdRedir < 0){
            perror("Can't Open");
            exit(1);
        }

        if(dup2(fdRedir, STDOUT_FILENO) == -1){
            perror("dup2 failed");
            exit(1);
        }


    } 
    execvp(supplement[0], supplement);
    /* return only when exec fails */
    perror("exec failed");
    exit(-1);

1 Answer 1

2

The prototype of open is :

#include <fcntl.h>  
int open(const char *path, int oflag, ...);

When the file is created, you should give the file mode.

int open(const char *path, int oflags, mode_t mode);

In your code, the file is opened with flag O_CREAT but the file mode is not given. So you don't have the permission to operate on it. Try to indicate the file permission when create the new file:

int fdRedir = open(redirectName, O_WRONLY | O_CREAT, 0644);
Sign up to request clarification or add additional context in comments.

2 Comments

+1: Strictly, the prototype of open() is int open(const char *path, int oflag, ...);, but the net result is pretty much as you say: if you specify O_CREAT, you need to specify the third argument too. Without that, it is indeterminate what value is treated as the mode; from the result, it appears that the answer is 1.
@JonathanLeffler Thanks for giving the more strict prototype, I updated the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.