int main(void){
int n, user_length;
char userid[30];
char password[11];
if ((n = read(STDIN_FILENO, userid, 10)) == -1) {
perror("read");
exit(1);
} else if(n == 0) {
fprintf(stderr, "Error: could not read from stdin");
exit(1);
}
if (userid[n-1] == 'n')
userid[n-1] = ' ';
else
userid[n] = ' ';
if ((n = read(STDIN_FILENO, password, 10)) == -1) {
perror("read");
exit(1);
} else if (n == 0) {
fprintf(stderr, "Error: could not read from stdin");
exit(1);
}
if (password[n-1] == 'n')
password[n-1] = ' ';
else
password[n] = ' ';
strcat(userid, ":");
user_length = strlen(userid);
strcat(userid, password);
FILE *fp = fopen(PASSWORD_FILE, "r");
if (!fp) {
perror("fopen");
exit(1);
}
char line[MAXLINE];
while(fgets(line, sizeof(line) - 1, fp)) {
line[strlen(line) - 1] = ' ';
if (strcmp(userid, line) == 0)
exit(0); // found match
else if(strncmp(userid, line, user_length) == 0)
exit (2); // invalid password
}
exit(3); // no such user
}
以上是 validate.c 的实现,但是如何使用 pipe(),dup2 或 execl() 将用户 id 和密码等值传递给函数
我使用了以下内容'
int main(void) {
char userid[10];
char password[10];
int pid;
int p[2][4];
char other[MAXSIZE];
/* Read a user id and password from stdin */
printf("User id:n");
scanf("%s", userid);
printf("Password:n");
scanf("%s", password);
/*Your code here*/
if (pipe(p[1]) == -1) {
perror("pipe");
}
if (pipe(p[0]) == -1) {
perror("pipe");
}
pid = fork();
if (pid != 0) {
close(p[1][0]);
close(p[0][0]);
dup2(p[1][1],STDIN_FILENO);
dup2(p[0][1],STDIN_FILENO);
close(p[1][1]);
close(p[0][1]);
int status;
if (wait(&status)!= -1) {
if (WIFEXITED(status)) {
printf("[%d] Child exited with %dn", getpid(), WEXITSTATUS(status));
switch(WEXITSTATUS(status)){
case 0:
printf("found matchn");
break;
case 2:
printf("invalid passwordn");
break;
case 3:
printf("No such usern");
break;
default:
printf("error has occurn");
break;
};
} else {
printf("[%d] Child exited abnormallyn", getpid());
}
}
} else if (pid == 0) {
close(p[1][1]);
close(p[0][1]);
dup2(p[1][0], fileno(stdout));
dup2(p[1][0], fileno(stdout));
execl("validate",other);
printf("whatn");
close(p[1][0]);
close(p[0][0]);
} else {
perror("fork");
exit(1);
}
return 0;
}
但是提示总是要求我重新输入。这种方法有什么问题?(注意:我"execl"验证",因为它是已经创建的可执行文件。我写的execl()只是调用validate.c函数)
正如我在评论中所说,您可能不需要为此生成另一个进程,但是您调用execl的方式有错误。
这:
execl("validate",other);
应该是:
execl(filename,list of arguments, NULL);
这是文档页面。他们使用 (char *) 0,这与使用 NULL 相同。