简体   繁体   中英

Fork and Pipe problem - unlimited printing

After launching this code in int main():

int p[2];
char *argv[2];
argv[0] = "wc";
argv[1] = "0";
pipe(p);
if(fork() == 0) {
    close(0);
    dup(p[0]);
    close(p[0]);
    close(p[1]);
    execv("/bin/wc", argv);
} else {
    close(p[0]);
    write(p[1], "pls work finally jesus\n", 12);
    close(p[1]);
}

I end up with unlimited "> > > > > > > > > > > > > (...)" constantly printing in my terminal. How can i fix that?

Per the POSIX execv() documentation (bolding mine):

int execv(const char *path, char *const argv[]);

...

The argument argv is an array of character pointers to null-terminated strings. The application shall ensure that the last member of this array is a null pointer. ...

This does not meet those conditions:

char *argv[2];
argv[0] = "wc";
argv[1] = "0";

"0" is not a "null pointer". You're assigning the address of a string literal that contains the string "0" to argv[1] . Since the last member of the array isn't a "null pointer", you're invoking undefined behavior.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM