简体   繁体   中英

How to execute an a.out file by using exec function family in Linux

The aim of this c++ program is about the understanding the cocurrent process mechanism in operating system. And the following code is for the child functions of one process. And the child process have theirs numbers, NO.5 and NO.6.

I'm trying to exectute an a.out file in the NO.6 process. I'm trying to do it this way.

void ChildFunction_For_ProcessNO.4(int i){
    switch(i){
        case(5):
            cout << "This is process five, and the ID for this process is " << getpid() << '\n'
                 << "and the ID for the parent process is " << getppid() << '\n';
            CreateThreads_Five();
            cout << "Process five has ended.\n" << '\n';
            break;
        case(6):
            cout << "This is process six, and the ID for this process is " << getpid() << '\n'
                 << "and the ID for the parent process is " << getppid() << '\n';
            execl("./a.out", "a.out", NULL);
            //and I also tried this way
            execl("Home/CLionProjects/Project_1/a.out", "a.out", NULL);
            char buf[100]; 
            cout << "getcwd: " << getcwd(buf, sizeof(buf))) << endl;
            cout << "Process six has ended.\n";
            break;
    }

and the getcwd's output goes like this

getcwd: /home/chengxuyuan/CLionProjects/Project_1/cmake-build-debug

The a.out file has already been put in the folder together with the c++ program. the screenshot of the working directory and the compile went well, but there is just no output which ought to be Hello world from the a.out file. How can I solve this problem. Thanks a lot!

The getcwd output shows that you have to put your file a.out into

/home/chengxuyuan/CLionProjects/Project_1/cmake-build-debug

Your attempt

execl("Home/CLionProjects/Project_1/a.out", "a.out", NULL);

is wrong this is not the full path. You would have to use

execl("/home/chengxuyuan/CLionProjects/Project_1/a.out", "a.out", NULL);

BTW: You should specify the same value as argument 0 as you use for the program to be run, ie

execl("/home/chengxuyuan/CLionProjects/Project_1/a.out", "/home/chengxuyuan/CLionProjects/Project_1/a.out", NULL);

or

execl("./a.out", "./a.out", NULL);

This is what the shell would do and what most programs expect.

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