LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   calling a shell script from exec. (https://www.linuxquestions.org/questions/programming-9/calling-a-shell-script-from-exec-938852/)

ankitm 04-09-2012 04:12 AM

calling a shell script from exec.
 
Hi ,

I was trying to use exec to run a shell script

#include<stdio.h>
#include<unistd.h>
int main(int argc,char *argv[])
{
unsigned int child;
switch(child=fork())
{
case 0:
printf("in child");
execv("./check_script",NULL);
break;
case -1:
printf("Error");
break;
default:
printf("Parent %d",child);
break;
}
return 0;
}
However on executing the above code , I am getting the following output.
/a.out
Parent 17507in child
check_script just echoes a String .

Please explain this behaviour.

Ajit Gunge 04-09-2012 05:40 AM

Can you share the contents of your check_script?

ankitm 04-09-2012 05:43 AM

Hi,
It just echoes iniside script.
vi ./check_script
echo "Inside script"

Thanks..

Nominal Animal 04-09-2012 05:53 AM

Please use [CODE] [/CODE] tags around your code, to make it readable.

Quote:

Originally Posted by ankitm (Post 4648156)
execv("./check_script",NULL);

There is the first part of your problem. If you look at the man 3 execv man page, you'll see that the first parameter is the path to the file, and the second parameter is the argument array. The argument array itself cannot be empty, as the first entry in the array must be the script name. The last entry in the array must be NULL.

I often use something like
Code:

char *args[2] = { "./check_script", NULL };

execv(args[0], args);

especially if I have parameters I wish to supply to the script. If you don't need to supply any arguments to the script, you might wish to use execl instead:
Code:

execl("./check_script", "./check_script", NULL);
The first parameter is the path to the script, and the second parameter is the script name. If you add echo "$0" in ./check_script, you can output the script name, as seen by the script itself.

Just remember that the path to the script is first, then the script name -- in both argument array and execl() parameter list --, followed by parameters, followed by NULL, and that neither the path to the script nor the script name can be NULL.

The second part of your problem is that you are missing the shebang line, which tells the kernel which shell interpreter to use:
Code:

#!/bin/bash
echo "This is ./check_script, '$0'."

Hope this helps,

ankitm 04-09-2012 06:05 AM

Thanks for help ...


All times are GMT -5. The time now is 02:07 AM.