[Linux环境变成]Linux设置子进程环境变量

时间:2022-09-16 00:52:03

posix_spawn通过一个指定的可执行文件创建子进程,并设置其启动参数和环境变量。其原型如下:

#include <spawn.h>

// pid:子进程的进程号
// path:创建子进程的可执行文件路径
// file_actions:与文件相关的操作
// attrp:进程属性
// argv:子进程的启动参数
// envp:子进程的环境变量
int posix_spawn(pid_t *pid, const char *path,
                       const posix_spawn_file_actions_t *file_actions,
                       const posix_spawnattr_t *attrp,
                       char *const argv[], char *const envp[]);

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

例子

我们在main.cc中创建一个子进程,并且通过posix_spawn为子进程设置进程的启动参数、环境变量,然后在子进程输出相关信息,代码和makefile分别如下:

main.cc

// main.cc
#include <unistd.h>
#include <stdio.h>
#include <iostream>
#include <spawn.h>


int main(int argc,char *argv[])
{
    char *file = "/home/lighthouse/workspace/linux-action/02-posix-spawn-envp/child_process";
    pid_t pid;
    char *envp[] = {
        "PATH=/usr/sbin",
        "WORKSPACE=/workspace",
        "UMASK=007",
        nullptr
    };

    char *_argv[] = {
        "ttl",
        "500",
        "delay",
        "999",
        nullptr
    };
    int ret = posix_spawn(&pid,file,nullptr,nullptr,_argv,envp);

    if (ret != 0)
    {
        std::cout << "spawn failed,file:" << file << ",code:" << ret << std::endl;
    }

    pause();   
    return 0;// this is comment
}

child_process.cc

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

extern char **environ;


int main(int argc,char *argv[])
{
    char **env = environ;
    if (environ == nullptr)
    {
        std::cout << "nullptr envp" << std::endl;
    }

    while (*env != nullptr)
    {
        std::cout << *env << std::endl;
        env++;
    }

    std::cout << "arg count:" << argc << std::endl;
    for (int i = 0;i < argc;++i)
    {
        std::cout << argv[i] << " ";
    }
    std::cout << std::endl;
    pause();
    return 0;// this is comment
}

Makefile

C = gcc
CXX = g++
SOURCE_C = 
OBJECTS_C = 
SOURCE_CXX = child_process.cc
TARGET = child_process
LDFLAGS_COMMON = -std=c++2a


MAIN_CXX = main.cc
MAIN_TARGET = main

all:
	$(CXX) $(SOURCE_CXX)  $(LDFLAGS_COMMON) -o $(TARGET)
	$(CXX) $(MAIN_CXX)  $(LDFLAGS_COMMON) -o $(MAIN_TARGET)
clean:
	rm -rf *.o $(TARGET) ${MAIN_TARGET}