最近项目中需要用C语言实现Linux用户和用户组的创建,需要在C语言中调用adduser等命令。因为adduser这类命令需要在命令行中进行输入交互,不能通过system函数来实现,所以想要用进程管道来进行进程间的输入交互。
下面是我用进程管道实现的具体代码,希望对有类似需求的同学有帮助。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int adduser(char *user, char *home, char *passwd)
{
int status = 0;
FILE * fd = NULL;
char cmd[1024] = {0};
char param[256] = {0};
/* get adduser shell command */
sprintf(cmd, "adduser --home %s %s >> /dev/null 2>&1", home, user);
fd = popen(cmd, "w");
if (!fd) {
printf("create adduser pipe failed.\n");
return -1;
}
/* get password */
sprintf(param, "%s\n", passwd);
/* Enter new UNIX password */
status = fwrite(param, 1, strlen(param), fd);
if (status < 0) {
printf("write pipe failed.\n");
goto error;
}
/* Retype new UNIX password */
status = fwrite(param, 1, strlen(param), fd);
if (status < 0) {
printf("write pipe failed.\n");
goto error;
}
/* get other param */
memset(param, 0, sizeof(param));
sprintf(param, "\n\n\n\n\n\n");
/* pass other options */
status = fwrite(param, 1, strlen(param), fd);
if (status < 0) {
printf("write pipe failed.\n");
goto error;
}
pclose(fd);
/* check new user */
memset(cmd, 0, sizeof(cmd));
sprintf(cmd, "cat /etc/group | grep %s", user);
fd = popen(cmd, "r");
if (!fd) {
printf("create check user pipe failed.\n");
return -1;
}
status = fread(param, 1, sizeof(param), fd);
if (status <= 0) {
printf("adduser failed.\n");
goto error;
}
pclose(fd);
return 0;
error:
pclose(fd);
return -1;
}
int main(void)
{
int status = 0;
status = adduser("mm", "/home/zzs/work/test", "123123");
if (!status) {
printf("adduser success!!!\n");
}
return 0;
}