- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在创建一个有2个进程的客户端程序:一个父进程定期向服务器传输数据以使其知道客户端仍然处于连接状态,以及一个子进程接收用户输入并将其发送到服务器,如果该输入恰好是“#EXIT”,则子进程将让父进程知道程序需要通过共享内存中的变量终止,然后退出。问题是在程序打印任何内容之前我就遇到了段错误。
奇怪的是,我第一次运行它时,它给出了预期的输出,并在我输入“#EXIT”时终止,但我随后运行它时,它立即出现了 seg 错误。一开始我以为是因为最后没有调用shm_unlink
,但是我加上了,结果是一样的。然后我认为这是因为我没有在子进程上调用 exit
,但我添加了它,结果再次是相同的。
客户端代码:
#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <stdbool.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <stdlib.h>
int main(int argc, char const *argv[])
{
if (argc-1 != 2){
perror("Usage: ./351ChatClient [address] [port]");
return -1;
}
int sock = 0, valread;
struct sockaddr_in serv_addr;
char buffer[1024] = {0};
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("\n Socket creation error \n");
return -1;
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(atoi(argv[2]));
// Convert IPv4 and IPv6 addresses from text to binary form
if(inet_pton(AF_INET, argv[1], &serv_addr.sin_addr)<=0)
{
printf("\nInvalid address/ Address not supported \n");
return -1;
}
if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
{
printf("\nConnection Failed \n");
return -1;
}
int* shared_memory;
int shm_fd = shm_open("Transmitting", O_CREAT | O_EXCL | O_RDWR, S_IRWXU | S_IRWXG);
ftruncate(shm_fd, sizeof(int));
shared_memory = (int *) mmap(NULL, sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);
shared_memory[0] = 0;
int pid = fork();
if (pid == 0){
char data[256];
while (strcmp(data, "#EXIT") != 0){
fgets(data, sizeof(data), stdin);
data[strlen(data)-1] = '\0';
send(sock , data, strlen(data) , 0 );
valread = read( sock , buffer, 1024);
printf("%s\n",buffer );
}
shared_memory[0] = 1;
exit(EXIT_SUCCESS);
}
else if (pid > 0){
while(shared_memory[0] == 0){
// transmit data every couple seconds to let server know client is still connected
}
shm_unlink("Transmitting");
printf("Stopped transmitting\n");
}
return 0;
}
服务器代码:
#include <stdio.h>
#include <sys/socket.h> //For Sockets
#include <stdlib.h>
#include <netinet/in.h> //For the AF_INET (Address Family)
#include <string.h>
#include <stdbool.h>
#include <unistd.h>
#define MAXSIZE 256
void add_user(char name[], char password[]){
if (strlen(name) > MAXSIZE || strlen(password) > MAXSIZE){
// send error message to client
return;
}
FILE* fp = fopen("users.txt", "a");
char s[strlen(name)+strlen(password)+2];
strcpy(s, name);
strcat(s, "\n");
strcat(s, password);
strcat(s, "\n");
fputs(s, fp);
fclose(fp);
}
void connect_user(char name[], char password[]){
FILE* fp = fopen("users.txt", "r");
char line[MAXSIZE];
char cur_name[MAXSIZE];
bool match = false;
int line_no = 1;
while (fgets(line, sizeof(line), fp)){
line[strlen(line)-1] = '\0'; // remove trailing newline
if (line_no % 2 != 0){
strcpy(cur_name, line);
if (strcmp(cur_name, name) == 0){
match = true;
}
}
else if(match){
if (strcmp(line, password) == 0){
char s[strlen(cur_name)+strlen(" is entering the queue\n")];
strcpy(s, cur_name);
strcat(s, " is entering the queue\n");
printf("%s", s);
// add user to the queue
return;
}
else{
// send invalid password message to client
return;
}
}
line_no = line_no + 1;
}
add_user(name, password); // if user not found, add it to the DB
}
int main(int argc, char *argv[]){
FILE* fp = fopen("users.txt", "a"); // creates users file if it does not exist
fclose(fp);
int sockfd, newsockfd, portno;
socklen_t clilen;
char buffer[256];
struct sockaddr_in serv_addr, cli_addr;
int n;
if (argc < 2) {
fprintf(stderr, "ERROR, no port provided\n");
exit(1);
}
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
perror("ERROR opening socket");
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
perror("ERROR on binding");
listen(sockfd, 5);
clilen = sizeof(cli_addr);
//Below code is modified to handle multiple clients using fork
//------------------------------------------------------------------
int pid;
while (1) {
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
if (newsockfd < 0)
perror("ERROR on accept");
//fork new process
pid = fork();
if (pid < 0) {
perror("ERROR in new process creation");
}
if (pid == 0) {
//child process
close(sockfd);
//do whatever you want
bzero(buffer, 256);
while(strcmp(buffer, "#EXIT") != 0){
memset(buffer, 0, sizeof(buffer)); // clear the read buffer
n = read(newsockfd, buffer, 255);
if (n < 0)
perror("ERROR reading from socket");
printf("Here is the message: %s\n", buffer);
n = write(newsockfd, "I got your message", 18);
if (n < 0)
perror("ERROR writing to socket");
}
n = write(newsockfd, "See you soon!", 18);
if (n < 0)
perror("ERROR writing to socket");
printf("Closing connection with client");
close(newsockfd);
exit(EXIT_SUCCESS);
} else {
//parent process
close(newsockfd);
}
}
//-------------------------------------------------------------------
return 0;
}
当我输入“#EXIT”时,我期望收到的输出是
#EXIT
Stopped transmitting
但是我收到的输出很简单
segmentation fault (core dumped)
在我有机会输入任何内容之前。
我对 c 套接字和一般的 c 都很陌生,所以请毫不犹豫地指出我是否做了其他完全错误的事情。谢谢。
编辑:我注意到的另一件事是,当客户端出现段错误时,服务器会收到大量消息。但不知道为什么。
编辑2:我注释掉了客户端中的所有套接字代码,重新编译并执行它,仍然发生段错误。
编辑3:我在定义数据之前修复了 while 循环检查数据,但问题仍然存在。
这是简化的客户端代码:
#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <stdbool.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <stdlib.h>
int main(int argc, char const *argv[])
{
if (argc-1 != 2){
perror("Usage: ./351ChatClient [address] [port]");
return -1;
}
int* shared_memory;
int shm_fd = shm_open("Transmitting", O_CREAT | O_EXCL | O_RDWR, S_IRWXU | S_IRWXG);
ftruncate(shm_fd, sizeof(int));
shared_memory = (int *) mmap(NULL, sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);
shared_memory[0] = 0;
int pid = fork();
if (pid == 0){
char data[256];
while (true){
fgets(data, sizeof(data), stdin);
data[strlen(data)-1] = '\0';
if(strcmp(data, "#EXIT") != 0)
break;
}
shared_memory[0] = 1;
exit(EXIT_SUCCESS);
}
else if (pid > 0){
while(shared_memory[0] == 0){
// transmit data every couple seconds to let server know client is still connected
}
shm_unlink("Transmitting");
printf("Stopped transmitting\n");
}
return 0;
}
编辑4:我使用命令valgrind --leak-check=full --track-origins=yes ./351ChatClient 127.0.0.1 8080
通过valgrind运行客户端,这就是我得到的:
==11098== Memcheck, a memory error detector
==11098== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==11098== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==11098== Command: ./351ChatClient 127.0.0.1 8080
==11098==
==11098== Invalid write of size 4
==11098== at 0x108AA4: main (in /home/jp/Courses/csci351/projects/project1/351ChatClient)
==11098== Address 0xffffffffffffffff is not stack'd, malloc'd or (recently) free'd
==11098==
==11098==
==11098== Process terminating with default action of signal 11 (SIGSEGV)
==11098== Access not within mapped region at address 0xFFFFFFFFFFFFFFFF
==11098== at 0x108AA4: main (in /home/jp/Courses/csci351/projects/project1/351ChatClient)
==11098== If you believe this happened as a result of a stack
==11098== overflow in your program's main thread (unlikely but
==11098== possible), you can try to increase the size of the
==11098== main thread stack using the --main-stacksize= flag.
==11098== The main thread stack size used in this run was 8388608.
==11098==
==11098== HEAP SUMMARY:
==11098== in use at exit: 0 bytes in 0 blocks
==11098== total heap usage: 0 allocs, 0 frees, 0 bytes allocated
==11098==
==11098== All heap blocks were freed -- no leaks are possible
==11098==
==11098== For counts of detected and suppressed errors, rerun with: -v
==11098== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
Segmentation fault (core dumped)
最佳答案
您的段错误错误可能源于add_user(...)
和connect_user(中的
函数,因为 free(s)
...)char s[...]
是堆栈上可变大小的数组,没有分配给堆来空闲
。你需要摆脱它们。
在服务器端和客户端,您不需要使用 wait(..)
或 waitpid(..)
来等待子进程
此外,最好使用 0
来初始化数组,例如char arr[SIZE] = {0}
,也适用于可变大小的数组。
AFAI 还知道,bzero
已被弃用并降低了可移植性。所以你应该使用 memset(..)
来代替。
n = write(newsockfd, "See you Soon!", 18);
在第 128 行,剩下的 5
个字符(字节)怎么样?垃圾文章?
更好地使用 -Weverything
标志。
shared_memory[0] = 0;
?
如果shm_open(..)
返回-1
怎么办?在这种情况下,您确定 shared_memory
指向您可以写入的合法位置吗?您应该始终特别注意返回值及其结果。
int shm_fd = shm_open("Transmitting", O_CREAT | O_EXCL | O_RDWR, S_IRWXU | S_IRWXG);
if (shm_fd == -1) {
perror("shm_fd error");
exit(-1);
}
在我的计算机中,一次性运行后会产生 shm_fd 错误:文件存在
。
请记住,非匿名共享映射对象会保留在计算机中,除非手动删除或通过 unlink(..)
或 remove(..)
或者,只需删除 O_EXCL
标志即可。
关于c - C套接字客户端程序中2个进程之间使用共享内存会导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57997520/
我使用下拉菜单提供一些不同的链接,但我希望这些链接在同一选项卡中打开,而不是在新选项卡中打开。这是我找到的代码,但我对 Javascript 非常缺乏知识 var urlmenu = docume
我对 javascript 不太了解。但我需要一个垂直菜单上的下拉菜单,它是纯 JavaScript,所以我从 W3 复制/粘贴脚本:https://www.w3schools.com/howto/t
我已经坐了 4 个小时,试图让我的导航显示下 zipper 接垂直,但它继续水平显示它们。我无法弄清楚为什么会发生这种情况或如何解决它。 如果有人能告诉我我做错了什么,我将不胜感激。我有一个潜移默化的
我正在尝试创建选项卡式 Accordion 样式下拉菜单。我使用 jQuery 有一段时间了,但无法使事件状态达到 100%。 我很确定这是我搞砸的 JS。 $('.service-button').
对于那些从未访问过 Dropbox 的人,这里是链接 https://www.dropbox.com/ 查看“登录”的下拉菜单链接。我如何创建这样的下 zipper 接? 最佳答案 这是 fiddle
我正在制作一个 Liferay 主题,但我在尝试设计导航菜单的样式时遇到了很多麻烦。我已经为那些没有像这样下拉的人改变了导航链接上的经典主题悬停功能: .aui #navigation .nav li
如果您将鼠标悬停在 li 上,则会出现一个下拉菜单。如果您将指针向下移至悬停时出现的 ul,我希望链接仍然带有下划线,直到您将箭头从 ul 或链接移开。这样你就知道当菜单下拉时你悬停在哪个菜单上。 知
我有一个带有多个下拉菜单的导航栏。因此,当我单击第一个链接时,它会打开下拉菜单,但是当我单击第二个链接时,第一个下拉菜单不会关闭。 (所以如果用户点击第二个链接我想关闭下拉菜单) // main.js
我正在尝试制作一个导航下拉菜单(使用 Bootstrap 3),其中链接文本在同一行上有多个不同的对齐方式。 在下面的代码中,下拉列表 A 中的链接在 HTML 中有空格字符来对齐它们,但是空白被忽略
我希望有人能帮我解决这个 Bootstrap 问题,因为我很困惑。 有人要求我在底部垂直对齐图像和其中包含图像的链接。 我面临的问题是他们还希望链接在链接/图像组合上具有 pull-right,这会杀
我正在构建一个 Rails 应用程序,并希望指向我的类的每个实例的“显示”页面的链接显示在“索引”页面的下拉列表中。我目前正在使用带有 options_from_collection_for_sele
我有以下 Bootstrap3 导航菜单 ( fiddle here )。我想设置“突出显示”项及其子链接与下拉列表 1 和 2 链接不同的链接文本(和悬停)的样式。我还希望能够以不同于 Highli
我对导航栏中的下拉菜单有疑问。对于普通的导航链接(无下拉菜单),我将菜单文本放在 H3 中,但是当我尝试对下 zipper 接执行相同操作时,箭头不在标题旁边,而是在标题下方。我决定用 span 替换
我是一名优秀的程序员,十分优秀!