我正在编写这个程序,创建一个父母和一个孩子,我必须验证一个用户名。 但似乎它没有工作,因为我有一个全局变量集,所以我可以直接跳过一些代码块到我想要评估用户名的部分。 但似乎我拥有的变量logEval并没有保留我在第一个子节点中给出的值,所以它在父节点内返回0。
这是代码:
var timeout;
$("#iframe").attr("src", "url-cross-domain.html").on("load", function() {
clearTimeout(timeout);
console.log("loaded !");
}):
timeout = setTimeout(function() {
$("#iframe").off("load").remove();
console.error("iframe loading failed");
}, 60000);
第二次编辑:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <fcntl.h>
//sys variables
char Input[100], commandLogin[100], Output[100], Username[50], possibleUsername[50];
int readDescriptor, logEval;
pid_t childPid;
//
int commandCatcher(){
//define socket
int socketOne[2], socketTwo[2];
if(socketpair(AF_UNIX, SOCK_STREAM, 0, socketOne) < 0){
perror("socket - err");
exit(0);
}
if(logEval == 0)
switch(fork()){//first child
case -1:
perror("fork - err");
exit(1);
case 0:
childPid=getpid();
readDescriptor = read(socketOne[0], commandLogin, sizeof(commandLogin));
if (strcmp(commandLogin, "login") == 0 ){
logEval = logEval + 1;
printf("Log eval from first:%d\n", logEval);
write(socketOne[0], "ok", strlen("ok") + 1);
//something to do here so that the child knows it was given the username
exit(1);
}
else {
printf("Try again.\n");
write(socketOne[0], "none", strlen("none")+1);
exit(1);
}
}
if(logEval == 1){
switch(fork()){//verify username
case -1:
perror("fork - err");
exit(2);
case 0:
readDescriptor = read(socketTwo[0], possibleUsername, sizeof(possibleUsername));
printf("Username from second child:%s\n", possibleUsername);
printf("logEval is : %d", logEval);
}
exit(2);
}
//parent
//getting initial value
scanf("%s", Input);
//writing initial value
write(socketOne[1], Input, strlen(Input)+1);
readDescriptor = read(socketOne[1], Output, sizeof(Output));
//printf("output %s\n", Output);
//verify if the command was correctly given
if(strcmp(Output, "ok") == 0) {
printf("Command was accepted. Insert your username: %d\n", logEval);
if(socketpair(AF_UNIX, SOCK_STREAM, 0, socketTwo) < 0){//second socket
perror("sockettwo - err");
exit(2);
}
scanf("%s", Username);
write(socketTwo[1], Username, strlen(Username)+1);
printf("%s\n", Username);
printf("%d\n", logEval);
commandCatcher();
}
else if(strcmp(Output, "none") == 0) {
printf("Command was denied. Please try again:\n");
commandCatcher();//recursive call
}
wait(&childPid);
printf("execution finished");
}
int main(){
printf("Welcome to Sys v1.0. To start off, please insert your command. \n");
commandCatcher();
return 0;
}
答案 0 :(得分:1)
当您fork()
进程时,它的孩子无法访问父母的地址空间。它将拥有它的完整副本,因此在fork()
之前设置的任何内容在子项中都是相同的,但如果您更新子进程内的任何内容,则父进程将不会看到它。您需要为此使用某种形式的进程间通信(IPC),例如共享内存或管道。