linux 应用层调用shell指令api.之popen 和system

popen 和system测试

test.c

#include
#include
#include 

int main()
{
	FILE *fp1 = NULL;
	fp = popen("sudo systemctl enable ssh","w");//使用popen 发送打开ssh的指令
	if(fp == nullptr)
	{
		printf(" open error");
		return -1;
	}
	
	fp = popen("mypasswd123","w");使用popen 发送执行密码,非root用户,执行系统指令时,需要输入系统密码
	if(fp == nullptr)
	{
		printf("popen("mypasswd123","w") error");
		return -1;
	}
	pclose(fp);
	
	int ret = -1;
	ret = system("sudo systemctl start ssh");使用system发送启动ssh的指令
	if(ret < 0)
	{
		printf(" system("sudo systemctl start ssh") error");
		return -1;
	}
	
        return 1;
}

你可能感兴趣的:(linux,应用和网络开发,linux)