我正在学习使用Linux中的套接字设置客户端服务器通信的教程。我在strftime()调用中观察SIGSEGV分段错误。我试过调试值,不知道故障在哪里。有人可以帮忙吗?
int socketOk;
int fds[2];
pid_t child_proc;
socketOk = socketpair(AF_LOCAL, SOCK_STREAM, 0, fds);
if((child_proc = fork()) == (pid_t) -1) {
//Fork Failure case
printf("\n ERR-%s: fork() failed \n", strerror(errno));
}
else if(child_proc == 0) {
//Fork Child case
printf("\n Child: Child process created under Server PID - %d \n", getppid());
close(fds[0]);
fds[0] = -1;
printf("\n Child: Requesting Date in a specific format from Server");
char *timeFormatPtrChild;
//timeFormatPtrChild = "%Y-%m-%d %I:%M:%S";
timeFormatPtrChild = "%A %d-%b-%Y %l:%M %p";
int writeOk = write(fds[1], timeFormatPtrChild, strlen(timeFormatPtrChild));
printf("\n Child: Request sent to Server - %s \n", (writeOk==-1 ? "Unsuccessful" : "Successful"));
char timeStringChild[50];
int readOk = read(fds[1], timeStringChild, sizeof timeStringChild);
timeStringChild[readOk] = 0;
if(readOk >= 0) {
printf("\n Child: Date received from server - %s \n", timeStringChild);
}
else {
printf("\n ERR-%s: read() failed in client \n", strerror(errno));
}
fflush(stdout);
close(fds[0]);
}
else {
//Fork Parent case
close(fds[1]);
fds[1]=-1;
printf("\n Server: Child process created with PID-%d \n", child_proc);
printf("\n Server: Waiting for Child request");
char timeString[80];
char timeFormatPtr[50];
int readOk = read(fds[0], timeFormatPtr, sizeof timeFormatPtr);
printf("\n Server: Received Time format from Child - %s \n", (readOk==-1 ? "Unsuccessful" : timeFormatPtr));
timeFormatPtr[readOk] = 0;
time_t timePtr;
time(&timePtr);
strftime(timeString, sizeof timeString, timeFormatPtr, localtime(&timePtr));
int writeOk = write(fds[0], timeString, strlen(timeString));
if(writeOk >= 0) {
printf("\n Server: Date sent to Child - %s \n", timeString);
}
else {
printf("\n ERR-%s: write() failed in Server \n", strerror(errno));
}
int status;
close(fds[0]);
waitpid(child_proc, &status, 0);
}
return 0;
}