C语言多线程自动化部署linux环境

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_30115765/article/details/52957289

1.创建多任务并行

/*************************************************************************
    > File Name: pipe6.c
    > Author: zhuan
    > Mail: 2065286676@qq.com
    > Created Time: 20161018日 星期二 152337************************************************************************/

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

int main(){
    int data_processed=0;
    int filedes[2];
    const char data[] = "Hello pipe!";
    char buffer[BUFSIZ+1];
    pid_t pid;

    memset(buffer,'\0',sizeof(buffer));
    printf("%d\n",filedes[0]);
    printf("%d\n",filedes[1]);

    if(pipe(filedes)==0)
    {
        pid =fork();
        if(pid==-1)
        {
            fprintf(stderr,"FROK failure");
            exit(EXIT_FAILURE);
        }else if(pid==0)
        {   
            printf("%d\n",filedes[0]);
            data_processed = read(filedes[0],buffer,BUFSIZ);
            printf("Read %d bytes:%s\n",data_processed,buffer);
            exit(EXIT_SUCCESS);
        }else{
            sleep(3);
            data_processed=write(filedes[1],data,strlen(data));
            printf("Wrote %d bytes:%s\n",data_processed,data);
            sleep(2);
            exit(EXIT_SUCCESS);
        }

    }
    exit(EXIT_FAILURE);
}

2.执行shell命令的三种方式

1、system(执行shell 命令)

相关函数 fork,execve,waitpid,popen
表头文件 #include

#include<stdlib.h>
main()
{
system(“ls -al /etc/passwd /etc/shadow”);
}

2、popen(建立管道I/O)

相关函数 pipe,mkfifo,pclose,fork,system,fopen
表头文件 #include

#include<stdio.h>
main()
{
FILE * fp;
char buffer[80];
fp=popen(“cat /etc/passwd”,”r”);
fgets(buffer,sizeof(buffer),fp);
printf(“%s”,buffer);
pclose(fp);
}

3、使用vfork()新建子进程,然后调用exec函数族

#include<unistd.h>
main()
{
    char * argv[ ]={“ls”,”-al”,”/etc/passwd”,(char*) };

    if(vfork() = =0)
    {
        execv(“/bin/ls”,argv);
    }else{        
        printf(“This is the parent process\n”);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_30115765/article/details/52957289