본문 바로가기

Linux

system() 함수 (c언어로 쉘 호출하기)

반응형


[형태] 

#include <stdlib.h>
int system(const char *str)


[기능]

system() 함수는 실행 쉘인 /bin/sh -c str 을 호출하여 str에 지정된 명령어를 실행하고

명령어가 끝난 뒤 리턴한다. 명령어가 실행되는 동안은 SIGCHLD(자식 프로세스가 종료되었을 때 나오는 signal)는 block되며

SIGINT(키보드 interrupt로 실행중지시키는 signal, ctrl+c), SIGQUIT(키보드 interrupt로 프로세스 종료 + 코어덤프, ctrl+₩) 는 무시된다.

(fork() + execve() 조합이라고 생각하면 된다)


[반환값]

return 127 : /bin/sh를 실행시키위한 execve() 실패 시,

return -1 : 에러 발생

return 그 외 값 : 명령어(str에 적은)의 return 값 


[예제]

1
2
3
4
5
6
7
8
9
10
11
12
#include <stdio.h>
#include <stdlib.h>
 
int main()
{
    int ret = system("ls -l");
 
    printf("ret : %d \n", ret);
 
    return 0;
}
 
cs

위 코드를 컴파일해서 실행해보면 우리가 쉘에서 ls -l을 친 것과 동일한 결과를 확인할 수 있다.

성공했다면 ret : 0 이 출력 될 것이다. 



참고] ls 리턴값

EXIT STATUS

The following exit values shall be returned:

 0
Successful completion.
>0
An error occurred.

출처 : https://pubs.opengroup.org/onlinepubs/009695399/utilities/ls.html



반응형