Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

In "Why? Motivating The API", some problems #51

Open
eric49861 opened this issue Nov 19, 2022 · 0 comments
Open

In "Why? Motivating The API", some problems #51

eric49861 opened this issue Nov 19, 2022 · 0 comments

Comments

@eric49861
Copy link

eric49861 commented Nov 19, 2022

When I write code in "p4.c" like:

close(STDOUT_FILENO);
open("./info.output", O_CREAT | O_WRONLY | O_TRUNC, S_IRWXU);

I can't get the output of another programme which i want to execute in the subprocess with system call "execvp" from "info.output", but when i write the above code in another file (like "wc.c"), it recovers normal.
So, i want to know whether i write wrong code or the book with something wrong.

all code i write:
p2.c

#include "stdio.h"
#include "stdlib.h"
#include "unistd.h"
#include "string.h"
#include "sys/wait.h"
#include "fcntl.h"

int main(int argc, char **argv){
    printf("hello world (pid:%d)\n", (int)getpid());
    int rc = fork();
    if(rc < 0){
        fprintf(stderr, "fork failed\n");
        exit(1);
    }else if(rc == 0){
        printf("hello, I am child (pid:%d)\n", (int)getpid());
        //if i write them here, i can't get output from info.output
        //close(STDOUT_FILENO);
        //open("./info.output", O_CREAT | O_WRONLY | O_TRUNC, S_IRWXU);
        char *myargs[3];
        myargs[0] = strdup("./test");

        if(myargs[0] == NULL){
            fprintf(stderr, "malloc failed");
        }

        myargs[1] = strdup("--parameter");
        if(myargs[1] == NULL){
            fprintf(stderr, "malloc failed");
        }

        myargs[2] = NULL;
        execvp(myargs[0], myargs);
        printf("this statement shouldn't be executed");
    }else{
        //wait subprocess to finish, return pid of subprocess
        int wc = wait(NULL);
        printf("%d\n", wc);
        printf("hello, I am parent of %d (pid:%d)\n", rc, (int)getpid());
    }
    return 0;
}

test.c

#include "stdio.h"
#include "stdlib.h"
#include "unistd.h"
#include "string.h"
#include "sys/wait.h"
#include "fcntl.h"

int main(int argc, char **argv){
    if(argc == 1){
        fprintf(stderr, "need a argument but no parameter");
        exit(1);
    }
//when i write them here, it's normal
    close(STDOUT_FILENO);
    open("./info.output", O_CREAT | O_WRONLY | O_TRUNC, S_IRWXU);
    for(int i = 1; i < argc; i++){
        printf("%s\n", argv[i]);
    }
    return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant