逆向 | linux c fork子进程

逆向 | linux c fork子进程

参考文章:
https://blog.csdn.net/whatday/article/details/112093358

创建子进程

代码如下:

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


int main(){
	printf("@ test for subprocess \n");
	pid_t pid;
	int n;
	pid = fork();
	if (pid < 0){
		perror("fork failed");
		exit(1);
	}
	if (pid == 0){
		printf("> from child! pid: %d, ppid: %d \n", getpid(), getppid());
	}else{
		// printf("> from father! pid: %d, ppid: %d \n", getpid(), getppid());
		printf("> from father! pid: %d \n", getpid());
		sleep(1);
	}

	return 0;
}

如果不加sleep(),可能会出现父进程比子进程先退出的情况,子进程会被upstart这个进程收养,具体参考下面这个文章:
https://blog.csdn.net/Leafage_M/article/details/70273624

运行截图:
image

exec 执行别的进程

image

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


int main(){
	printf("@ test for subprocess \n");
	pid_t pid;
	int n;
	pid = fork();
	if (pid < 0){
		perror("fork failed");
		exit(1);
	}
	if (pid == 0){
		printf("> from child! pid: %d, ppid: %d \n", getpid(), getppid());
        char *argv[ ]={"ls", "-al", ".", NULL};  
        char *envp[ ]={"PATH=/bin", NULL};
        if(execve("/bin/ls", argv, envp) < 0)
        {
            printf("subprocess error");
            exit(1);
        }
        // 子进程要么从 ls 命令中退出,要么从上面的 exit(1) 语句退出
        // 所以代码的执行路径永远也走不到这里,下面的 printf 语句不会被执行
        printf("You should never see this message.");
	}else{
		printf("> from father! pid: %d \n", getpid());
		sleep(1);
	}

	return 0;
}

运行截图:
image

通过pipe与子进程交互读写:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>

char toExec[] = "/bin/python3";
char *argv[] = {toExec, "./subprocesstest.py", NULL};
char *envp[]={"PATH=/bin", NULL};

int main(){
	printf("@ test for subprocess \n");
	pid_t pid;
	int child_output[2];
	int child_input[2];
	
	int status;
	
	// create pipe for two process
	if (pipe(child_output) < 0) {
		perror("pipe err \n");
		exit(1);
	}
	if (pipe(child_input) < 0) {
		perror("pipe err \n");
		exit(1);
 	}
 
 	// create child
	pid = fork();
	if (pid < 0){
		perror("fork failed");
		exit(1);
	}
	
	// child
	if (pid == 0){
		//将子进程的输出由标准输出重定向到 cgi_ouput 的管道写端上
		dup2(child_output[1], 1);
		//将子进程的输出由标准输入重定向到 cgi_ouput 的管道读端上
		dup2(child_input[0], 0);
		//关闭 ouput 管道的读端与input 管道的写端
		close(child_output[0]);
		close(child_input[1]);
  
        if(execve(toExec, argv, envp) < 0)
        {
            printf("subprocess execve error");
            exit(1);
        }
	}
	// father
	else{
		//父进程则关闭了output管道的写端和 input 管道的读端
		close(child_output[1]);
		close(child_input[0]);
		
		//然后从 child_output 管道中读子进程的输出
		char c;
		printf("recv from child: \n");
		while (read(child_output[0], &c, 1) > 0){
			printf("%c", c);
		}
		//关闭管道
		close(child_output[0]);
		close(child_input[1]);
		//等待子进程的退出
		waitpid(pid, &status, 0);
	}

	return 0;
}
posted @ 2022-05-15 11:37  Mz1  阅读(109)  评论(0编辑  收藏  举报