简体   繁体   中英

c execute doesn't work

I try to execute a program with some arguments by a c-program. But it seems to doesn't work. Here is the code in c:

#include<stdio.h>
#include<unistd.h>

int main(int argc, char *argv[])
{
    int i;
        for (i = 0; i < 10; i++)
        {
                execl("tempo2","-gr fake","-f best.sim.par","-ndobs 30","-nobsd 1","-ha 12","-randha y","-start 57023","-end 60000","-rms 0.0012",NULL);
        }
    return 0;
}

I compile with gcc on Mint 17. When I run that c-program nothing happens. In bash it works and looks like this:

#!/bin/bash

for i in `seq 1 10`;
do
    tempo2 -gr fake -f best.sim.par -ndobs 30 -nobsd 1 -ha 12 -randha y -start 57023 -end 60000 -rms 0.0012
done

Can anyone translate me the bash code into c or tell what I did wrong? Thanks and happy hollydays

您可以使用system()函数而不是execl()来执行shell命令

system("tempo2 -gr fake -f best.sim.par -ndobs 30 -nobsd 1 -ha 12 -randha y -start 57023 -end 60000 -rms 0.0012");

check the return code. according to the man page,

The return value is -1, and errno is set to indicate the error.

i donnot have your program, but you need to specify the full path to "tempo2", or you will get errno 2 => no such file or directory.

The first argument to execl is the path to the program to run. The second argument is the value that appears in that program's argv[0] and is often the same. Thus, you should put "tempo2" twice in your argument list. Also, each space-separated word on the command line ahould be in a separate string. So instead of "-gr fake" , you should use "-gr","fake" .

All told, your execl call should look like this:

execl("tempo2","tempo2","-gr","fake","-f","best.sim.par","-ndobs","30","-nobsd","1","-ha","12","-randha","y","-start","57023","-end","60000","-rms","0.0012",NULL);

Finally, one important thing about execl . It replaces the current process with the new program. Thus, even though it's in a loop, tempo2 will only be run once . To do what you're trying to do, you need to use fork to create a child process to run each execl .

All told, you're probably better off using system as @SunDro suggested.

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