How to reply a D-Bus message - glib

I got the D-Bus server.c and client.c code, and made some modification.
I want the result that when type for example "hi" from client.c
server will print "receive message hi", and reply "reply_content!!!!!!" to client.c
But it seems that now client.c cannot get the reply message.
Anyone have the idea?
Thanks in advance.
"server.c"
/* server.c */
#include <dbus/dbus.h>
#include <stdbool.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
static DBusHandlerResult
filter_func(DBusConnection *connection, DBusMessage *message, void *usr_data)
{
DBusMessage *reply;
dbus_bool_t handled = false;
char *word = NULL;
DBusError dberr;
dbus_error_init(&dberr);
dbus_message_get_args(message, &dberr, DBUS_TYPE_STRING, &word, DBUS_TYPE_INVALID);
printf("receive message: %s\n", word);
handled = true;
reply = dbus_message_new_method_return(message);
char * reply_content = "reply_content!!!!!!";
dbus_message_append_args(reply, DBUS_TYPE_STRING, &reply_content, DBUS_TYPE_INVALID);
dbus_connection_send(connection, reply, NULL);
dbus_connection_flush(connection);
dbus_message_unref(reply);
return (handled ? DBUS_HANDLER_RESULT_HANDLED : DBUS_HANDLER_RESULT_NOT_YET_HANDLED);
}
int main(int argc, char *argv[])
{
DBusError dberr;
DBusConnection *dbconn;
dbus_error_init(&dberr);
dbconn = dbus_bus_get(DBUS_BUS_SESSION, &dberr);
if (!dbus_connection_add_filter(dbconn, filter_func, NULL, NULL)) {
return -1;
}
dbus_bus_add_match(dbconn, "type='signal',interface='client.signal.Type'", &dberr);
while(dbus_connection_read_write_dispatch(dbconn, -1)) {
/* loop */
}
return 0;
}
Here is client.c
#include <dbus/dbus.h>
#include <stdbool.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
static DBusHandlerResult
filter_func(DBusConnection *connection, DBusMessage *message, void *usr_data)
{
dbus_bool_t handled = false;
char *word = NULL;
DBusError dberr;
dbus_error_init(&dberr);
dbus_message_get_args(message, &dberr, DBUS_TYPE_STRING, &word, DBUS_TYPE_INVALID);
printf("receive message %s\n", word);
handled = true;
return (handled ? DBUS_HANDLER_RESULT_HANDLED : DBUS_HANDLER_RESULT_NOT_YET_HANDLED);
}
int db_send(DBusConnection *dbconn)
{
DBusMessage *dbmsg;
char *word = (char *)malloc(sizeof(char));
int i;
dbmsg = dbus_message_new_signal("/client/signal/Object", "client.signal.Type", "Test");
scanf("%s", word);
if (!dbus_message_append_args(dbmsg, DBUS_TYPE_STRING, &word, DBUS_TYPE_INVALID)) {
return -1;
}
if (!dbus_connection_send(dbconn, dbmsg, NULL)) {
return -1;
}
dbus_connection_flush(dbconn);
printf("send message %s\n", word);
dbus_message_unref(dbmsg);
return 0;
}
int main(int argc, char *argv[])
{
DBusError dberr;
DBusConnection *dbconn;
dbus_error_init(&dberr);
dbconn = dbus_bus_get(DBUS_BUS_SESSION, &dberr);
if (!dbus_connection_add_filter(dbconn, filter_func, NULL, NULL)) {
return -1;
}
db_send(dbconn);
while(dbus_connection_read_write_dispatch(dbconn, -1)) {
db_send(dbconn);
}
dbus_connection_unref(dbconn);
return 0;
}

You're communicating only with signals at the moment, which don't have a return value.
In client.c, use dbus_message_new_method_call instead of dbus_message_new_signal, and in server.c you probably have to change type='signal' to type='method_call'.

Related

pthread error code 3025 (ENOENT) on the as400/IBM i?

When I have the following C source code, which is running on an IBM i Midrange, then I get a non-zero result from pthread_create, specifically 3025, which is ENOENT (No such path or directory), which doesn't make any sense to me. Anyone have any thoughts on what the error actually means in this context.
#define _MULTI_THREADED
#define _XOPEN_SOURCE 520
#include <pthread.h>
#include <stdio.h>
#include <errno.h>
void* workerThread(void* parm) {
// Do some work here
pthread_exit(NULL);
}
int main(int argc, char* argv[]) {
pthread_t t;
int rc;
rc = pthread_create(&t, NULL, workerThread, NULL);
if (rc != 0) {
char *msg = strerror(errno);
perror("pthread_create failed");
}
// Other code here
return 0;
}
pthread_create doesn't set errno. You should be checking strerror of rc.
http://pubs.opengroup.org/onlinepubs/7908799/xsh/pthread_create.html
char *msg = strerror(rc);

read event never triggered, using libevent

I just write an echo server using libevent, but it seems that the read event is never triggered. The code is:
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <netinet/tcp.h>
#include <event.h>
#include <event2/event.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <errno.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <arpa/inet.h>
static short ListenPort = 19999;
static long ListenAddr = INADDR_ANY;//任意地址,值就是0
static int MaxConnections = 1024;
static int ServerSocket;
static struct event ServerEvent;
int SetNonblock(int fd)
{
int flags;
if ((flags = fcntl(fd, F_GETFL)) == -1) {
return -1;
}
if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) {
return -1;
}
return 0;
}
void ServerRead(int fd, short ev, void *arg)
{
//1)when telnet on 1999 and send a string,this never prints,help!
printf("client readble\n");
fflush(stdout);
struct client *client = (struct client *)arg;
u_char buf[8196];
int len, wlen;
len = read(fd, buf, sizeof(buf));
if (len == 0) {
printf("disconnected\n");
close(fd);
event_del(&ServerEvent);
free(client);
return;
} else if (len < 0) {
printf("socket fail %s\n", strerror(errno));
close(fd);
event_del(&ServerEvent);
free(client);
return;
}
wlen = write(fd, buf, len);//1)client str never echo back
if (wlen < len) {
printf("not all data write back to client\n");
}
}
void ServerWrite(int fd, short ev, void *arg)
{
//2)to be simple,let writer do nothing
/* if(!arg)
{
printf("ServerWrite err!arg null\n");
return;
}
int len=strlen(arg);
if(len <= 0)
{
printf("ServerWrite err!len:%d\n",len);
return;
}
int wlen = write(fd, arg, len);
if (wlen<len) {
printf("not all data write back to client!wlen:%d len:%d \n",wlen,len);
}
*/
return;
}
void ServerAccept(int fd, short ev, void *arg)
{
int cfd;
struct sockaddr_in addr;
socklen_t addrlen = sizeof(addr);
int yes = 1;
cfd = accept(fd, (struct sockaddr *)&addr, &addrlen);
if (cfd == -1) {
//3)this prints ok
printf("accept(): can not accept client connection");
return;
}
if (SetNonblock(cfd) == -1) {
close(cfd);
return;
}
if (setsockopt(cfd, IPPROTO_TCP, TCP_NODELAY, &yes, sizeof(yes)) == -1) {
printf("setsockopt(): TCP_NODELAY %s\n", strerror(errno));
close(cfd);
return;
}
event_set(&ServerEvent, cfd, EV_READ | EV_PERSIST, ServerRead, NULL);
event_set(&ServerEvent, cfd, EV_WRITE| EV_PERSIST, ServerWrite,NULL);
event_add(&ServerEvent, NULL);
printf("Accepted connection from %s \n", (char *)inet_ntoa(addr.sin_addr));
}
int NewSocket(void)
{
struct sockaddr_in sa;
ServerSocket = socket(AF_INET, SOCK_STREAM, 0);
if (ServerSocket == -1) {
printf("socket(): can not create server socket\n");
return -1;
}
if (SetNonblock(ServerSocket) == -1) {
return -1;
}
memset(&sa, 0, sizeof(sa));
sa.sin_family = AF_INET;
sa.sin_port = htons(ListenPort);
sa.sin_addr.s_addr = htonl(ListenAddr);
if (bind(ServerSocket, (struct sockaddr*)&sa, sizeof(sa)) == -1) {
close(ServerSocket);
printf("bind(): can not bind server socket");
return -1;
}
if (listen(ServerSocket, MaxConnections) == -1) {
printf("listen(): can not listen server socket");
close(ServerSocket);
return -1;
}
event_set(&ServerEvent, ServerSocket, EV_READ | EV_PERSIST, ServerAccept, NULL);
if (event_add(&ServerEvent, 0) == -1) {
printf("event_add(): can not add accept event into libevent");
close(ServerSocket);
return -1;
}
return 0;
}
int main(int argc, char *argv[])
{
int retval;
event_init();
retval = NewSocket();
if (retval == -1) {
exit(-1);
}
event_dispatch();
return 0;
}
The server is tested using Telnet, but the client receives nothing.
The question details are posted as comments in the code above, at 1)、2)、3).
Can someone help me find out why the read event is never triggered?
basically you should not set the accepted socket as EV_WRITE until you actually want to write to the socket. You are telling libevent "let me know when I can write to this socket", which is pretty much always. So ServerWrite is being called in a tight loop. In practice the only time you need EV_WRITE is if you are writing a buffer but all of the bytes are not written. You then need to save the unwritten portion of the buffer and use EV_WRITE to signal when the socket can be written to again.

Setsockopt() returning error number 10042

So I am getting started with SCTP and have written the basics of the SCTP server application(which I intend to modify to make it a peer-to-peer app). The code is incomplete but I compiled and ran it to test the socket options and the first setsockopt returns error 10042(protocol not supported). I have determined that it's the first call of setsockopt() that returns an error. So here is the incomplete code:
#include "stdafx.h"
#include <iostream>
#include <iostream>
#include <string.h>
#include <stdlib.h>
#ifndef UNICODE
#define UNICODE
#endif
#define WIN32_LEAN_AND_MEAN
#include <WinSock2.h>
#include <WS2tcpip.h>
#include <WS2spi.h>
#include <ws2sctp.h>
#include <wsipv6ok.h>
#include <if.h>
#include "ws2isatap.h"
#include "if_tunnel.h"
#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "sctpsp.lib")
using namespace std;
using namespace System;
static int LISTENQ = 5;
void isatap_enable(void);
int main(int argc, char* argv[]){
WSADATA wsaData;
int iResult;
int optv = 10;
u_long imode = 1;
bool connected = false;
char *optval = (char*)&optv;
int optlen = sizeof(optval);
sockaddr_in6 servAddr;
sctp_sndrcvinfo sr;
sctp_event_subscribe evnts;
sctp_initmsg init;
memset(&sr,0,sizeof(sr));
memset(&evnts,0,sizeof(evnts));
memset(&init,0,sizeof(init));
memset(&servAddr,0,sizeof(servAddr));
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != NO_ERROR) {
wprintf(L"WSAStartup function failed with error: %d\n", iResult);
return 1;
}
SOCKET servSock = socket(AF_INET6,SOCK_STREAM,IPPROTO_SCTP);
if(servSock==INVALID_SOCKET){
printf("Socket function failed with error: %d\n",GetLastError());
return 1;
}
if(setsockopt(servSock,IPPROTO_IPV6,IPV6_PROTECTION_LEVEL,optval,sizeof(optval))<0){
printf("setsockopt function failed with error: %d\n", GetLastError());
return 1;
}
u_int servPort = 5000;
servAddr.sin6_family = AF_INET6;
servAddr.sin6_addr = in6addr_any;
servAddr.sin6_port = htons(servPort);
if(setsockopt(servSock,IPPROTO_SCTP,SCTP_EVENTS,(const char*)&evnts,sizeof(evnts)) < 0){
printf("setsockopt function failed with error: %d\n", GetLastError());
return 1;
}
ioctlsocket(servSock,FIONBIO, &imode);
if(bind(servSock,(struct sockaddr*)&servAddr,sizeof(servAddr))<0){
printf("Bind function failed with error: %d\n", GetLastError());
return 1;
}
evnts.sctp_data_io_event = 1;
evnts.sctp_association_event = *(u_char*)optval;
for(;;){
if(listen(servSock,LISTENQ) < 0){
printf("Listen function failed with error: %d/n",GetLastError());
return 1;
}else{
printf("Listening on port %d\n",servPort);
}
}
}
If it's related to python packages nameko/kombu/amqp, then it's reported here Issue with 2.1.4 version.
Temporary soln: Roll-back the version to 2.1.3 till it's fixed.
OK guys, I fixed it(for now lol). What I did is substitute the IPPROTO_IPV6 with IPPROTO_SCTP and it seems to work.

CodeBook background subtraction with moving objects

I am trying to use CodeBook method for OpenCV to subtract the background. So far so good, but I am not sure if I can update the codebook for moving objects after some time span, say 5 minutes, I need to update the codebook after which I get lots of moving objects. How do I make sure that after 5 minutes I have a background that needs to be updated?
Thanks for the tips!
kim's algorithm supposedly has a cache layer, i did not dig deep enough into opencv implementation to know how to have a workable version that works with exposure problem.
notes
opencv book(which i havent read) should have the info you need if it's there at all
this is only 1 channel and not in yuv although it can be extended
needs more work on speed/testing (you can of course turn on optimization in compiler)
background subtraction is a buzzy word. try "change detection"
bgfg_cb.h
#ifndef __bgfg_cb_h__
#define __bgfg_cb_h__
//http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.148.9778&rep=rep1&type=pdf
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <iostream>
#include <time.h>
using namespace cv;
using namespace std;
struct codeword {
float min;
float max;
float f;
float l;
int first;
int last;
bool isStale;
};
extern int alpha ;
extern float beta ;
extern int Tdel ,Tadd , Th;
void initializeCodebook(int w,int h);
void update_cb(Mat& frame);
void fg_cb(Mat& frame,Mat& fg);
#endif
bgfg_cb.cpp
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <iostream>
#include <time.h>
#include "bgfg_cb.h"
using namespace cv;
using namespace std;
vector<codeword> **cbMain;
vector<codeword> **cbCache;
int t=0;
int alpha = 10;//knob
float beta =1;
int Tdel = 200,Tadd = 150, Th= 200;//knobs
void initializeCodebook(int w,int h)
{
cbMain = new vector<codeword>*[w];
for(int i = 0; i < w; ++i)
cbMain[i] = new vector<codeword>[h];
cbCache = new vector<codeword>*[w];
for(int i = 0; i < w; ++i)
cbCache[i] = new vector<codeword>[h];
}
void update_cb(Mat& frame)
{
if(t>10) return;
for(int i=0;i<frame.rows;i++)
{
for(int j=0;j<frame.cols;j++)
{
int pix = frame.at<uchar>(i,j);
vector<codeword>& cm =cbMain[i][j];
bool found = false;
for(int k=0;k<cm.size();k++)
{
if(cm[k].min<=pix && pix<=cm[k].max && !found)
{
found=true;
cm[k].min = ((pix-alpha)+(cm[k].f*cm[k].min))/(cm[k].f+1);
cm[k].max = ((pix+alpha)+(cm[k].f*cm[k].max))/(cm[k].f+1);
cm[k].l=0;
cm[k].last=t;
cm[k].f++;
}else
{
cm[k].l++;
}
}
if(!found)
{
codeword n={};
n.min=max(0,pix-alpha);
n.max=min(255,pix+alpha);
n.f=1;
n.l=0;
n.first=t;
n.last=t;
cm.push_back(n);
}
}
}
t++;
}
void fg_cb(Mat& frame,Mat& fg)
{
fg=Mat::zeros(frame.size(),CV_8UC1);
if(cbMain==0) initializeCodebook(frame.rows,frame.cols);
if(t<10)
{
update_cb(frame);
return;
}
for(int i=0;i<frame.rows;i++)
{
for(int j=0;j<frame.cols;j++)
{
int pix = frame.at<uchar>(i,j);
vector<codeword>& cm = cbMain[i][j];
bool found = false;
for(int k=0;k<cm.size();k++)
{
if(cm[k].min<=pix && pix<=cm[k].max && !found)
{
cm[k].min = ((1-beta)*(pix-alpha)) + (beta*cm[k].min);
cm[k].max = ((1-beta)*(pix+alpha)) + (beta*cm[k].max);
cm[k].l=0;
cm[k].first=t;
cm[k].f++;
found=true;
}else
{
cm[k].l++;
}
}
cm.erase( remove_if(cm.begin(), cm.end(), [](codeword& c) { return c.l>=Tdel;} ), cm.end() );
fg.at<uchar>(i,j) = found?0:255;
if(found) continue;
found = false;
vector<codeword>& cc = cbCache[i][j];
for(int k=0;k<cc.size();k++)
{
if(cc[k].min<=pix && pix<=cc[k].max && !found)
{
cc[k].min = ((1-beta)*(pix-alpha)) + (beta*cc[k].min);
cc[k].max = ((1-beta)*(pix+alpha)) + (beta*cc[k].max);
cc[k].l=0;
cc[k].first=t;
cc[k].f++;
found=true;
}else
{
cc[k].l++;
}
}
if(!found)
{
codeword n={};
n.min=max(0,pix-alpha);
n.max=min(255,pix+alpha);
n.f=1;
n.l=0;
n.first=t;
n.last=t;
cc.push_back(n);
}
cc.erase( remove_if(cc.begin(), cc.end(), [](codeword& c) { return c.l>=Th;} ), cc.end() );
for(vector<codeword>::iterator it=cc.begin();it!=cc.end();it++)
{
if(it->f>Tadd)
{
cm.push_back(*it);
}
}
cc.erase( remove_if(cc.begin(), cc.end(), [](codeword& c) { return c.f>Tadd;} ), cc.end() );
}
}
}
main.cpp
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "bgfg_cb.h"
#include <iostream>
using namespace cv;
using namespace std;
void proc()
{
Mat frame,fg,gray;
VideoCapture cap("C:/Downloads/S2_L1.tar/S2_L1/Crowd_PETS09/S2/L1/Time_12-34/View_001/frame_%04d.jpg");
cap >> frame;
initializeCodebook(frame.rows,frame.cols);
for(;;)
{
cap>>frame;
cvtColor(frame,gray,CV_BGR2GRAY);
fg_cb(gray,fg);
Mat cc;
imshow("fg",fg);
waitKey(1);
}
}
int main(int argc, char ** argv)
{
proc();
cin.ignore(1);
return 0;
}

libxml2 HTML Parse, document from HtmlReadFile() always has a root header of (null)

I'm trying to use libxml to parse through some HTML.
Here's my code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <libxml/HTMLparser.h>
htmlDocPtr gethtml(char *doclocation,char *encoding) {
htmlDocPtr doc;
doc = htmlReadFile(doclocation, encoding, HTML_PARSE_NOBLANKS | HTML_PARSE_NOERROR | HTML_PARSE_NOWARNING | HTML_PARSE_NONET);
if (doc == NULL) {
fprintf(stderr, "Document not parsed successfully.\n");
return;
}
return doc;
}
void getroot(htmlDocPtr doc) {
xmlNode *cur = NULL;
cur = xmlDocGetRootElement(doc);
if (cur == NULL) {
fprintf(stderr, "empty document\n");
xmlFreeDoc(doc);
return;
}
printf("%s\n", *cur);
}
int main(void) {
char *website = "http://www.google.com/index.html";
char *encoding = "UTF-8";
htmlDocPtr doc;
doc = gethtml(website, encoding);
getroot(doc);
return 0;
}
When I run the program, it always prints out (null). I'm guessing that the document isn't getting parsed corrected during HtmlReadFile(), but I'm not sure how to correct it.
Any help would be appreciated

Resources