리눅스 시스템 네트워크 프로그래밍 (2) - 프로세스 (2)

이동욱

2021/07/04

Categories: 시스템 프로그래밍 Tags: 시스템 프로그래밍

posix_spawn 계열 함수


int posix_spawn(pid_t *restrict pid, const char *restrict path, const posix_spawn_file_actions_t *file_actions, const posix_spawnattr_t *restrict attrp, char *const argv[restrict], char *const envp[restrict]);

int posix_spawnp(pid_t *restrict pid, const char *restrict file, cosnt posix_spawn_file_actions_t *file_actions, const posix_spawnattr_t *restrict attrp, char *const argv[restrict], char *const envp[restrict]);

posix_spawn_file_actions_t 구조체 조작


int posix_spawn_file_actions_init(posix_spawn_file_actions_t *file_actions);
int posix_spawn_file_destroy(posix_spawn_file_actions_t *file_actions);
int posix_spawn_file_actions_addopen(posix_spawn_file_actions_t *restrict file_actions, int fildes, const char *restrict path, int oflag, mode_t mode);
int posix_spawn_file_actions_addclose(posix_spawn_file_actions_t *file_actions, int fildes);
int posix_spawn_file_actions_adddup2(posix_spawn_file_actions_t *file_actions, int fildes, int newfildes);
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <spawn.h>
#include <fcntl.h>
#include <string.h>

int main() {
	int ret_err = 0;
	pid_t pid_child;
	char buf_err[64];
	posix_spawn_file_actions_t posix_faction; /* file action struct */
	char *argv_child[] = { "forkexec_child", NULL };
	printf("Parent[%d]: Start\n", getpid());

	if((ret_err = posix_spawn_file_actions_init(&posix_faction)) != 0) { /* init */
		strerror_r(ret_err, buf_err, sizeof(buf_err));
		fprintf(stderr, "Fail: file_actions_init :%s\n", buf_err);
		exit(EXIT_FAILURE);
	}
	if ((ret_err = posix_spawn_file_actions_addopen(&posix_faction, 3,
					"pspawn.log", O_WRONLY | O_CREAT | O_APPEND, 0664 )) != 0) {
		strerror_r(ret_err, buf_err, sizeof(buf_err));
		fprintf(stderr, "Fail: file_actions_addopen: %s\n", buf_err);
		exit(EXIT_FAILURE);
	}
	ret_err = posix_spawn(&pid_child,
			argv_child[0],
			&posix_faction,
			NULL,
			argv_child,
			NULL);

	if ((ret_err = posix_spawn_file_actions_destroy(&posix_faction)) != 0) {
		strerror_r(ret_err, buf_err, sizeof(buf_err));
		fprintf(stderr, "Fail: file_actions_destory: %s\n", buf_err);
		exit(EXIT_FAILURE);
	}
	printf("Parent[%d]: Wait for child(%d)\n", getpid(), (int)pid_child);
	(void)wait(NULL);
	printf("Parent[%d]: Exit\n", getpid());
	return 0;
}

posix_spawnattr_t 구조체 조작


int posix_spawnattr_init(posix_spawnattr_t *attr);
int posix_spawnattr_destroy(posix_spawnattr_t *attr);

int posix_spawnattr_getflags(const posix_spawnattr_t *restrict attr, short *restrict flags);
int posix_spawnattr_setflags(posix_spawnattr_t *attr, short flags);

참고 문헌

>> Home