Alexandros Fotis
Alexandros Fotis

Reputation: 11

function from linux shell script not execute in c program

I have seen similar posts in stackoverflow and other sites but I cannot find solution to my problem.

I have the following consoleout.sh file:

#!/bin/sh

#this way works in c:
#echo "Hello World!"

#but in function does not work:
a(){
  echo "Hello World!"
}

Following C code:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    system(".  consoleout.sh"); 

    system("a");
    return 0;
}

Without system("./consoleout.sh"), it works fine.

Upvotes: 1

Views: 115

Answers (2)

Petr Skocik
Petr Skocik

Reputation: 60058

system() invokes a shell and waits for it to terminate. Another call to system() will create a different shell that starts from scratch.

To run your shell function, you need to do it from the shell where it was defined:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    return system( ".  consoleout.sh; a" ); 
}

Upvotes: 4

choroba
choroba

Reputation: 241838

Each system calls a new instance of the shell, the second one doesn't know anything about the functions defined in the first one. You can, though, call the function in the first shell:

system(". consoleout.sh ; a");

Upvotes: 3

Related Questions