I am programming for one of my project "Auction". I put all the conditions for login at both server and client side. My program runs better till some statements but in meanwhile server stops responding.
I research over that by putting print statements and over internet and I found that it is sync problem rather than coding. May be the reason would be different i am not sure.
I also want to mention that when I put "read()" on while condition, things are running as expected. Can anyone please tell me that how to remove/avoid this sync problem (may be something else rather than sync)?
Server.cpp (only some part which is running well)
while(((n = read(sockfd,buffer,4096))!=0)&&(l==false)) {
if(i==0) cout<<"Username:"<<buffer;
if(i==1) { l = true; cout<<"Password:"<<buffer; }
i++;
}
Server.cpp (part before modification that was stucked at i=1)
for(i=0; i<2; i++) { cout<<endl<<"i="<<i<<endl;
bzero(&buffer, sizeof(buffer));
if((n = read(sockfd,buffer,4096))==0) { cout<<"problem";
close(sockfd);
FD_CLR(sockfd, &allset);
client[i] = -1;
} else { cout<<buffer<<i<<endl; if(i==1) {cout<<"copied password"; }
if(i == 0) { cout<<"copied user";} }
Related
I have a homework about FTP using CSocket in C++.I use Mfc Dialog-based as interface for my application.Using multithreading to handle multi-clients (1 server - many clients). I use a button called "Listen".Everytime i hit the button,server start to listen. But the problem here,i put the Accecpt in a loop to handle muti-clients (each clients will go in a seperate thread), but now i cannot close the server-dialog whenever i want.It stucks in the "Listen" button forever.Can you give me some suggest to make it works.I did some research myself.I tried some techniques but it didn't work.
Thank you.
Please dont tell me about Select or Poll, I am using Windows not Linux.
I want to keep CSocket ,not Winsock. I tried to close listen in another thread ,but it didn't work.
void CServerDlg::OnBnClickedListen()
{
// TODO: Add your control notification handler code here
if (listen.Create(PORT, SOCK_STREAM, _T("127.0.0.1")) == 0) {
showMessage("Failed to init socket");
listen.GetLastError();
return;
}
else {
if (listen.Listen(1) == FALSE) {
showMessage("Can't listen to the port");
listen.Close();
return;
}
}
int cnt = -1;
CSocket* client;
while (1)
{
client = new CSocket();
if (listen.Accept(*client))
{
cnt++;
char * id = Converter::StringToChar(Converter::NumberToString(*client));
clients.push_back(client);
ClientId.push_back(id);
showMessage("Found a connection with client " + Converter::CharToString(id));
/*
Thread here
*/
threads.push_back(thread(&CServerDlg::ThreadProc, this, cnt));
}
else break;
}
listen.Close();
for (int i = 0; i < clients.size(); i++)
{
if (clients[i] != NULL)
{
clients[i]->Close();
}
}
clients.clear();
}
```
void CServerDlg::OnBnClickedCancel()
{
// TODO: Add your control notification handler code here
// i want every time i click 'cancel; button theaplcaton will clsoe
}
```
I'm trying to get the serial number of a USB device using libusb-1.0.
The problem I have is that sometimes the libusb_get_string_descriptor_ascii() function returns -7 (LIBUSB_ERROR_TIMEOUT) in my code, but other times the serial number is correctly written in my array and I can't figure out what is happening. Am I using libusb incorrectly? Thank you.
void EnumerateUsbDevices(uint16_t uVendorId, uint16_t uProductId) {
libusb_context *pContext;
libusb_device **ppDeviceList;
libusb_device_descriptor oDeviceDescriptor;
libusb_device_handle *hHandle;
int iReturnValue = libusb_init(&pContext);
if (iReturnValue != LIBUSB_SUCCESS) {
return;
}
libusb_set_debug(pContext, 3);
ssize_t nbUsbDevices = libusb_get_device_list(pContext, &ppDeviceList);
for (ssize_t i = 0; i < nbUsbDevices; ++i) {
libusb_device *pDevice = ppDeviceList[i];
iReturnValue = libusb_get_device_descriptor(pDevice, &oDeviceDescriptor);
if (iReturnValue != LIBUSB_SUCCESS) {
continue;
}
if (oDeviceDescriptor.idVendor == uVendorId && oDeviceDescriptor.idProduct == uProductId) {
iReturnValue = libusb_open(pDevice, &hHandle);
if (iReturnValue != LIBUSB_SUCCESS) {
continue;
}
unsigned char uSerialNumber[255] = {};
int iSerialNumberSize = libusb_get_string_descriptor_ascii(hHandle, oDeviceDescriptor.iSerialNumber, uSerialNumber, sizeof(uSerialNumber));
std::cout << iSerialNumberSize << std::endl; // Print size of serial number <--
libusb_close(hHandle);
}
}
libusb_free_device_list(ppDeviceList, 1);
libusb_exit(pContext);
}
I see nothing wrong with your code. I would not care to much about timeouts in the context of USB. It is a bus after all and can be occupied with different traffic.
As you may know there is depending on the version of USB a portion of the bandwidth reserved for control transfers. libusb_get_string_descriptor_ascii simply sends all the required control transfers to get the string. If any of those times out it will abort. You can try to send this control transfers yourself and use bigger timeout values but I guess the possibility of a timeout will always be there to wait for you (pun intended).
So it turns out my device was getting into weird states, possibly not being closed properly or the like. Anyway, calling libusb_reset_device(hHandle); just after the libusb_open() call seems to fix my sporadic timeout issue.
libusb_reset_device()
Hi I started learning Java and am currently trying to learn C++. I have this piece of code and cannot workout what it does. I am assuming it makes the program wait for a certain period of time before it starts. But some further explanation would very useful.
I have added comments to sections for which I would like some further explanation.
for (;;) {
wait (0.02); //What does this do?
if (ab1_On) {
con += 104;
ab1_On = 0; //Why is the value reset to 0?
}
if (ab2_On) {
con += 208;
ab2_On = 0; //Why is the value reset to 0?
}
con++;
if (con > 311) {
con -= 312;
}
for (int i=0; i<3; i++) {
bright[i] = brilvl (con + (i * 104));
}
}
}
wait() is a function defined in the mbed SDK.
https://developer.mbed.org/handbook/Wait
In your program wait(0.02) will block execution for 20 milliseconds.
for (;;) is an infinite loop, it will run forever. The wait() may be being used to prevent the effects of switch bounce if ab1_on and ab2_on are being set by some mechanical switch.
I'm writing a server for an online game based on IOCP, and the core codes handling game message is something like below:
CMessage ret;
int now_roomnum = recv_msg->para1;
int now_playernum = recv_msg->para2;
/*if(true)
{
cout<<"Received Game Message: "<<endl;
cout<<"type2 = "<<recv_msg->type2;
cout<<" player_num = "<<now_playernum<<" msg= "<<recv_msg->msg<<endl;
cout<<endl;
}*/
if(recv_msg->type2 == MSG_GAME_OPERATION)
{
ret.type1 = MSG_GAME;
ret.type2 = MSG_GAME_OPERATION;
while(game_host[now_roomnum].Ready(now_playernum) == true)
{
;
}
//cout<<"Entered from "<<now_playernum<<endl;
game_host[now_roomnum].SetMessage(now_playernum, recv_msg->msg);
game_host[now_roomnum].SetReady(now_playernum, true);
game_host[now_roomnum].SetUsed(now_playernum, false);
while(true)
{
bool tmp = game_host[now_roomnum].AllReady();
if(tmp == true)
break;
}
//cout<<"AllReady from"<<now_playernum<<endl;
string all_msg = game_host[now_roomnum].GetAllMessage();
game_host[now_roomnum].SetUsed(now_playernum, true);
while(!game_host[now_roomnum].AllUsed())
{
;
}
//cout<<"AllUsed from "<<now_playernum<<endl;
EnterCriticalSection(&cs);
game_host[now_roomnum].ClearReady();
LeaveCriticalSection(&cs);
strcpy_s(ret.msg, all_msg.c_str());
//cout<<"Return msg "<<now_playernum<<": "<<ret.msg<<endl;
}
return ret;
Now, the problem is: on a PC, when all cout are commented like above, the game freezes at once; but when I cancel the comments, the server works well.
What's more, when I run the server on my laptop, everything goes fine, no matter whether I comment the cout or not. The main difference between my laptop and PC is that my laptop's OS is Windows 8.1, while the PC is Windows 7.
I'm totally confused. It will be of great help if someone can tell me what to do. Thank you!
Looks like a multithreading issue.
By the way I see you use a Critical section around ClearReady but not when testing for AllReady. That call should be wrapped as well (or, better, write a LockedAllReady that makes use of the lock).
//cout<<"Return msg "<<now_playernum<<": "<<ret.msg<<endl;
What you mean by ret.msg? if msg is method you must do ret.msg(); , is it a field?
If you have this good then like they say above probably a timing problem, try to do cout without ret.msg and see what will happen, and then you know from where the problem is.
This question is the next step after resolving the issue discussed in:
Piping for input/output
I use pipes to pass a string via stdin to an external program called GULP, and receive the stdout of GULP as input for my program. This works fine on one processor, but on two or more processors there's a problem (let's say it's just 2 cores). The program GULP uses a temporary file and it seems that the two processors launch GULP simultaneously and then GULP tries to perform multiple operations on the same file at the same time (maybe simultaneous writes). GULP reports "error opening file".
I am testing this code on a laptop with multiple cores running Ubuntu, but the code is intended for a distributed-memory HPC (I'm using OpenMPI). Assume for the sake of this discussion that I cannot modify GULP.
I'm hoping that there's some straightforward way to get GULP to create two independent temporary files and continue functioning as normal. Am I asking for too much?
Hopefully this pseudo code will help (assume 2 processors):
int main()
{
MPI_Init(&argc,&argv);
MPI_Comm_rank(…);
MPI_Comm_size(…);
int loopmin, loopmax;//distributes the loop among each processor
for (int i = loopmin; i < loopmax; i++)
{
Launch_GULP(…);//launches external program
}
return 0;
}
Launch_GULP(…)
{
int fd_p2c[2], fd_c2p[2];
pipe(fd_p2c);
pipe(fd_c2p);
childpid = fork();
//the rest follows as in accepted answer in above link
//so i'll highlight the interesting stuff
if (childpid < 0)
{
perror("bad");
exit(-1);
}
else if (childpid == 0)
{
//call dup2, etc
execl( …call the program… );
}
else
{
//the interesting stuff
close(fd_p2c[0]);
close(fd_c2p[1]);
write(fd_p2c[1],…);
close(fd_p2c[1]);
while(1)
{
bytes_read = read(fd_c2p[0],…);//read GULP output
if (bytes_read <= 0)
break;
//pass info to read buffer & append null terminator
}
close(fd_c2p[0]);
if(kill(childpid,SIGTERM) != 0)
{
perror("Failed to kill child… tragic");
exit(1);
}
waitpid(childpid, NULL, 0);
}
//end piping… GULP has reported an error via stdout
//that error is stored in the buffer string
//consequently an error is triggered in my code and the program exits
}