exec를 이용하여 백그라운드에서 명령어 수행(유닉스환경)

pty1026의 이미지

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
 
int main(){
        char comman[10]={};
        void get_next_command(){
                gets(comman);
        }
 
 
        while(1){
                write(1,"input command:",14);
                get_next_command();
 
                int child=fork();
                if(child==0){
                        execlp(comman,"&",NULL);
                        exit(0);
                }
                else{
                        wait(child);
                }
        }
return 0;
}

여기서 어떻게 수정을 해야 할지 모르겠습니다.
execlp(comman,comman,NULL);
이렇게 였을 때는 수행이 포그라운드에서 수행이 잘 되는데
어떻게 백그라운드에서 수행하게 만들어야 되는지 조언부탁드립니다.

goforit의 이미지

출처)

http://codingfreak.blogspot.com/2012/03/daemon-izing-process-in-linux.html

#include <stdio.h>  
#include <stdlib.h>  
#include <unistd.h>  
#include <sys/types.h>  
#include <sys/stat.h>  
#include <fcntl.h>  
 
#define EXIT_SUCCESS 0  
#define EXIT_FAILURE 1  
 
static void daemonize(void)  
{  
    pid_t pid, sid;  
    int fd;   
 
    /* already a daemon */  
    if ( getppid() == 1 ) return;  
 
    /* Fork off the parent process */  
    pid = fork();  
    if (pid < 0)    
    {     
        exit(EXIT_FAILURE);  
    }     
 
    if (pid > 0)    
    {     
        exit(EXIT_SUCCESS); /*Killing the Parent Process*/  
    }     
 
    /* At this point we are executing as the child process */  
 
    /* Create a new SID for the child process */  
    sid = setsid();  
    if (sid < 0)    
    {  
        exit(EXIT_FAILURE);  
    }  
 
    /* Change the current working directory. */  
    if ((chdir("/")) < 0)  
    {  
        exit(EXIT_FAILURE);  
    }  
 
 
    fd = open("/dev/null",O_RDWR, 0);  
 
    if (fd != -1)  
    {  
        dup2 (fd, STDIN_FILENO);  
        dup2 (fd, STDOUT_FILENO);  
        dup2 (fd, STDERR_FILENO);  
 
        if (fd > 2)  
        {  
            close (fd);  
        }  
    }  
 
    /*resettign File Creation Mask */  
    umask(027);  
}  
 
int main( int argc, char *argv[] )  
{  
    daemonize();  
 
    while(1)  
    {  
      /* Now we are a daemon -- do the work for which we were paid */  
 
      sleep(10);  
    }  
 
    return 0;  
} 

goforit의 이미지

위에 소스 코드는 데몬으로 만들때, 거의 그대로 갔다쓰는 형식이구요, 때에 따라 setcap 이라는 systemcall 사용할 필요도 있습니다.

pty1026의 이미지

답변감사합니다! 근데 제가 궁금했던거는 exec를 이용해서 쉘 명령어를 수행하는거였습니다 ㅜㅜ
fork문을 사용하여 자식프로세스를 만들고 자식프로세스를 execlp를 이용하여 유닉스명령어를 수행하도록 만들었습니다.
그래서 이번에는 그 자식프로세스를 유닉스명령어를 수행하되 백그라운드에서 실행되도록 만들어보고싶었습니다
ls&처럼 &를 사용해야하는데 어떻게 짜야할지 모르겠더라구요 ㅜㅜ

pty1026의 이미지

답변감사합니다! 근데 제가 궁금했던거는 exec를 이용해서 쉘 명령어를 수행하는거였습니다 ㅜㅜ
fork문을 사용하여 자식프로세스를 만들고 자식프로세스를 execlp를 이용하여 유닉스명령어를 수행하도록 만들었습니다.
그래서 이번에는 그 자식프로세스를 유닉스명령어를 수행하되 백그라운드에서 실행되도록 만들어보고싶었습니다
ls&처럼 &를 사용해야하는데 어떻게 짜야할지 모르겠더라구요 ㅜㅜ

jick의 이미지

&는 exec 시리즈 명령어에서 인식하는 게 아니라 셸에서 인식하는 명령입니다. 즉 shell에다가 ls & 같은 명령을 내리면 셸이 알아서 "아 ls를 백그라운드로 돌리라는 말이구나"라고 해석하고 fork/exec하여 ls를 호출하게 됩니다. 이때 exec 명령에는 &를 주지 않습니다.

exec에 &를 주면 이는 셸에서 ls "&" 하는 것과 동일한 효과를 냅니다. (즉 ls를 실행시키면서 프로그램 인자로 &를 주는 것이죠.)

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.