简体   繁体   中英

C passing other c program as main argv

Just a curiosity,

Consider that I have

./first

./second

that they are executable c program

first.c:

char main(void){
    return '5';
}

second.c:

#include<stdio.h>
int main(int argc, char** argv){
    printf("%s", argv[2]);
    return 0;
}

(I want to print 5 here)

Is it possible to compile second.c like:

gcc second.c -./first

Of course I know that wont work but is it possible to write something that will work like what I want?

The return value of main() becomes the program's exit status, which is put in the shell's $? variable. So it should be:

./first
./second $?

You should change first.c to return an int , not char ; otherwise it will print the ASCII code for the '5' character, not 5 .

int main(void){
    return 5;
}

And in second.c , it should be argc[1] , not argv[2] .

Have the first program print "5":

int main(void){
    printf("5\n");
    return 0;
}

Then you can use backquotes in the shell to put the output of this program into the parameters of the other:

./second `./first`

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