linux c fork简单调用bin or shell script demo

来源:互联网 发布:格式化工厂软件 编辑:程序博客网 时间:2024/05/16 11:43

// exec shell script

#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
void hello()
{
  printf("hello word \n");
}

int main()
{
  pid_t pid;
  pid=fork();

  if(pid<0)
  {
    printf("fail to fork \n");
    exit(3);
  }
  else if(pid ==0)
  {

    // child process run  testcallexecl  
    //if(execl("/opt/test/testcallexecl","interp","arg1",NULL)<0)

   //  exec shell script /usr/bin/hello    must be set  x privilege to hello
    if(execl("/usr/bin/hello","xx","uu",NULL))
    {
       printf("fail to execl \n");
       exit(2);
    }
    printf("the child is not hello \n");
    exit(0);
  }
  printf("the parent %u\n",getpid());
  return 0;
}

 

cat /usr/bin/hello

  #!/bin/sh

  echo hello word

 

---------------------------------------------------------------------------------------------------

//  call bin

#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
int main()
{
  pid_t pid;
  pid=fork();

  if(pid<0)
  {
    printf("fail to fork \n");
    exit(3);
  }
  else if(pid ==0)
  {

    //exec testpid exec bin file
    if(execvp("testpid",NULL)<0)
    {

       //child process exec
       printf("fail to exec \n");
       exit(2);
    }
    printf("the child is not exec \n");
    exit(0);
  }
  printf("the parent %u\n",getpid());
  return 0;
}

 

 cat pid.c
#include<stdio.h>
#include<unistd.h>

int main()

{
  pid_t pid,ppid,uid,euid,gid,egid;

  pid=getpid();
  ppid=getppid();

  uid=getuid();
  euid=geteuid();

  gid=getgid();
  egid = getegid();

  printf("id of current process :%u \n",pid);
  printf("parent id of current process :%u \n",ppid);
  printf("user id of current process :%u \n",uid);
  printf("effective user id of current process :%u \n",euid);
  printf("gid of current process :%u \n",gid);
  printf("effective gid of current process :%u\n",egid);

  // setx pid  set gid
  if(setuid(501)==-1)
   {
     perror("fail to set uid");
     exit(1);
   }
  uid=getuid();
  euid=geteuid();
  printf("id of current process :%u \n",pid);
  printf("parent id of current process :%u \n",ppid);
  return 0;
}

 

0 0