本文整理汇总了C++中bzero函数的典型用法代码示例。如果您正苦于以下问题:C++ bzero函数的具体用法?C++ bzero怎么用?C++ bzero使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了bzero函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。
示例1: build_request
void build_request(const char *url)
{
char tmp[10];
int i;
bzero(host,MAXHOSTNAMELEN);
bzero(request,REQUEST_SIZE);
if(force_reload && proxyhost!=NULL && http10<1) http10=1;
if(method==METHOD_HEAD && http10<1) http10=1;
if(method==METHOD_OPTIONS && http10<2) http10=2;
if(method==METHOD_TRACE && http10<2) http10=2;
switch(method)
{
default:
case METHOD_GET: strcpy(request,"GET");break;
case METHOD_HEAD: strcpy(request,"HEAD");break;
case METHOD_OPTIONS: strcpy(request,"OPTIONS");break;
case METHOD_TRACE: strcpy(request,"TRACE");break;
}
strcat(request," ");
if(NULL==strstr(url,"://"))
{
fprintf(stderr, "\n%s: is not a valid URL.\n",url);
exit(2);
}
if(strlen(url)>1500)
{
fprintf(stderr,"URL is too long.\n");
exit(2);
}
if(proxyhost==NULL)
if (0!=strncasecmp("http://",url,7))
{ fprintf(stderr,"\nOnly HTTP protocol is directly supported, set --proxy for others.\n");
exit(2);
}
/* protocol/host delimiter */
i=strstr(url,"://")-url+3;
/* printf("%d\n",i); */
if(strchr(url+i,'/')==NULL) {
fprintf(stderr,"\nInvalid URL syntax - hostname don't ends with '/'.\n");
exit(2);
}
if(proxyhost==NULL)
{
/* get port from hostname */
if(index(url+i,':')!=NULL &&
index(url+i,':')<index(url+i,'/'))
{
strncpy(host,url+i,strchr(url+i,':')-url-i);
bzero(tmp,10);
strncpy(tmp,index(url+i,':')+1,strchr(url+i,'/')-index(url+i,':')-1);
/* printf("tmp=%s\n",tmp); */
proxyport=atoi(tmp);
if(proxyport==0) proxyport=80;
} else
{
strncpy(host,url+i,strcspn(url+i,"/"));
}
// printf("Host=%s\n",host);
strcat(request+strlen(request),url+i+strcspn(url+i,"/"));
} else
{
// printf("ProxyHost=%s\nProxyPort=%d\n",proxyhost,proxyport);
strcat(request,url);
}
if(http10==1)
strcat(request," HTTP/1.0");
else if (http10==2)
strcat(request," HTTP/1.1");
strcat(request,"\r\n");
if(http10>0)
strcat(request,"User-Agent: WebBench "PROGRAM_VERSION"\r\n");
if(proxyhost==NULL && http10>0)
{
strcat(request,"Host: ");
strcat(request,host);
strcat(request,"\r\n");
}
if(force_reload && proxyhost!=NULL)
{
strcat(request,"Pragma: no-cache\r\n");
}
if(http10>1)
strcat(request,"Connection: close\r\n");
/* add empty line at end */
if(http10>0) strcat(request,"\r\n");
// printf("Req=%s\n",request);
}
开发者ID:ssdr,项目名称:icl_lib,代码行数:93,代码来源:webbench.c
示例2: findRoots
static int findRoots(const QuadImplicitForm& i, const Quadratic& q2, double roots[4],
bool useCubic, bool& disregardCount) {
double a, b, c;
set_abc(&q2[0].x, a, b, c);
double d, e, f;
set_abc(&q2[0].y, d, e, f);
const double t4 = i.x2() * a * a
+ i.xy() * a * d
+ i.y2() * d * d;
const double t3 = 2 * i.x2() * a * b
+ i.xy() * (a * e + b * d)
+ 2 * i.y2() * d * e;
const double t2 = i.x2() * (b * b + 2 * a * c)
+ i.xy() * (c * d + b * e + a * f)
+ i.y2() * (e * e + 2 * d * f)
+ i.x() * a
+ i.y() * d;
const double t1 = 2 * i.x2() * b * c
+ i.xy() * (c * e + b * f)
+ 2 * i.y2() * e * f
+ i.x() * b
+ i.y() * e;
const double t0 = i.x2() * c * c
+ i.xy() * c * f
+ i.y2() * f * f
+ i.x() * c
+ i.y() * f
+ i.c();
#if QUARTIC_DEBUG
// create a string mathematica understands
char str[1024];
bzero(str, sizeof(str));
sprintf(str, "Solve[%1.19g x^4 + %1.19g x^3 + %1.19g x^2 + %1.19g x + %1.19g == 0, x]",
t4, t3, t2, t1, t0);
#endif
if (approximately_zero(t4)) {
disregardCount = true;
if (approximately_zero(t3)) {
return quadraticRootsX(t2, t1, t0, roots);
}
return cubicRootsX(t3, t2, t1, t0, roots);
}
if (approximately_zero(t0)) { // 0 is one root
disregardCount = true;
int num = cubicRootsX(t4, t3, t2, t1, roots);
for (int i = 0; i < num; ++i) {
if (approximately_zero(roots[i])) {
return num;
}
}
roots[num++] = 0;
return num;
}
if (useCubic) {
assert(approximately_zero(t4 + t3 + t2 + t1 + t0)); // 1 is one root
int num = cubicRootsX(t4, t4 + t3, -(t1 + t0), -t0, roots); // note that -C==A+B+D+E
for (int i = 0; i < num; ++i) {
if (approximately_equal(roots[i], 1)) {
return num;
}
}
roots[num++] = 1;
return num;
}
return quarticRoots(t4, t3, t2, t1, t0, roots);
}
开发者ID:mohamedkhairyhassan,项目名称:OsmAnd-external-skia,代码行数:66,代码来源:QuadraticImplicit.cpp
示例3: main
main()
{
int sockfd , clisockfd;
unsigned int clilen;
int childpid;
struct sockaddr_in serv_addr,cli_addr;
#ifdef LPR_with_ASUS//JY1112
int LPRflag = 0;
fd_set rfds, afds;
int nfds,nfds1;
int sockfd_ASUS;
unsigned int clilen_ASUS;
int childpid_ASUS;
struct sockaddr_in serv_addr_ASUS,cli_addr_ASUS;
#endif
#ifdef Raw_Printing_with_ASUS //Lisa
int netfd, fd, clientlen, one = 1;
struct sockaddr_in netaddr, client;
#endif
//Initial the server the not busy
lptstatus.busy = FALSE;
//Setup the signal handler
signal(SIGCLD, sig_child);
signal(SIGINT, sig_cleanup);
signal(SIGQUIT, sig_cleanup);
signal(SIGKILL, sig_cleanup);
signal(SIGUSR2, sig_remove);//JY1110
if((sockfd = socket(AF_INET,SOCK_STREAM,0)) < 0 )
{
perror("can't open stream socket:");
exit(0);
}
bzero((char *)&serv_addr , sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(PNT_SVR_PORT_LPR);
if(bind(sockfd,(struct sockaddr *)&serv_addr , sizeof(serv_addr)) < 0 )
{
perror("can't bind:");
exit(0);
}
/*JY1111*/
int windowsize=2920;
setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF, (char *)&windowsize, sizeof(windowsize));
#if 1
int currentpid=getpid();
FILE *pidfileread;
if((pidfileread=fopen("/var/run/lpdparent.pid", "r")) == NULL) {
pidfileread=fopen("/var/run/lpdparent.pid", "w");
fprintf(pidfileread, "%d", currentpid);
fclose(pidfileread);
}
else {
printf("another lpd daemon exists!!\n");
fclose(pidfileread);
exit(0);
}
#endif
/*JY1110
int testusb = 0;
testusb = check_par_usb_prn();
if(testusb){
printf("USB\n");//JY1112delete
fd_print=open("/dev/usb/lp0", O_RDWR);
}
else{
printf("PARALLEL\n");//JY1112delete
fd_print=open("/dev/lp0", O_RDWR);
}
checkstatus_usb_par();
close(fd_print);
111111*/
listen(sockfd , 15);
#ifdef Raw_Printing_with_ASUS //Lisa
if ((netfd = socket(AF_INET, SOCK_STREAM, IPPROTO_IP)) < 0)
{
// syslog(LOGOPTS, "socket: %m\n");
exit(1);
}
if (setsockopt(netfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) < 0)
{
// syslog(LOGOPTS, "setsocketopt: %m\n");
exit(1);
}
netaddr.sin_port = htons(BASEPORT);
netaddr.sin_addr.s_addr = htonl(INADDR_ANY);
memset(netaddr.sin_zero, 0, sizeof(netaddr.sin_zero));
if (bind(netfd, (struct sockaddr*) &netaddr, sizeof(netaddr)) < 0)
{
// syslog(LOGOPTS, "bind: %m\n");
//.........这里部分代码省略.........
开发者ID:nikatshun,项目名称:asuswrt-merlin,代码行数:101,代码来源:lpd_lisa.c
示例4: spec
NODE *
spec(void)
{
NODE *centry, *last;
char *p;
NODE ginfo, *root;
int c_cur, c_next;
char *buf, *tbuf = NULL;
size_t len;
last = root = NULL;
bzero(&ginfo, sizeof(ginfo));
centry = &ginfo;
c_cur = c_next = 0;
for (lineno = 1; (buf = fgetln(stdin, &len));
++lineno, c_cur = c_next, c_next = 0) {
/* Null-terminate the line. */
if (buf[len - 1] == '\n') {
buf[--len] = '\0';
} else {
/* EOF with no newline. */
tbuf = malloc(len + 1);
memcpy(tbuf, buf, len);
tbuf[len] = '\0';
buf = tbuf;
}
/* Skip leading whitespace. */
for (p = buf; isspace((unsigned char)*p); p++)
;
/* If nothing but whitespace or comment char, continue. */
if (*p == '\0' || *p == '#')
continue;
/* See if next line is continuation line. */
if (buf[len - 1] == '\\') {
c_next = 1;
if (--len == 0)
continue;
buf[len] = '\0';
}
#ifdef DEBUG
(void)fprintf(stderr, "line %d: {%s}\n", lineno, p);
#endif
if (c_cur) {
set(p, centry);
continue;
}
/* Grab file name, "$", "set", or "unset". */
if ((p = strtok(p, "\n\t ")) == NULL)
error("missing field");
if (p[0] == '/')
switch(p[1]) {
case 's':
if (strcmp(p + 1, "set"))
break;
set(NULL, &ginfo);
continue;
case 'u':
if (strcmp(p + 1, "unset"))
break;
unset(NULL, &ginfo);
continue;
}
if (strchr(p, '/'))
error("slash character in file name");
if (!strcmp(p, "..")) {
/* Don't go up, if haven't gone down. */
if (!root)
goto noparent;
if (last->type != F_DIR || last->flags & F_DONE) {
if (last == root)
goto noparent;
last = last->parent;
}
last->flags |= F_DONE;
continue;
noparent: error("no parent node");
}
len = strlen(p) + 1; /* NUL in struct _node */
if ((centry = calloc(1, sizeof(NODE) + len - 1)) == NULL)
error("%s", strerror(errno));
*centry = ginfo;
#define MAGIC "?*["
if (strpbrk(p, MAGIC))
centry->flags |= F_MAGIC;
if (strunvis(centry->name, p) == -1) {
fprintf(stderr,
"mtree: filename (%s) encoded incorrectly\n", p);
strlcpy(centry->name, p, len);
}
set(NULL, centry);
//.........这里部分代码省略.........
开发者ID:7shi,项目名称:openbsd-crosstools,代码行数:101,代码来源:spec.c
示例5: rp_pciattach
static int
rp_pciattach(device_t dev)
{
int num_ports, num_aiops;
int aiop;
CONTROLLER_t *ctlp;
int retval;
u_int32_t stcmd;
ctlp = device_get_softc(dev);
bzero(ctlp, sizeof(*ctlp));
ctlp->dev = dev;
ctlp->aiop2rid = rp_pci_aiop2rid;
ctlp->aiop2off = rp_pci_aiop2off;
ctlp->ctlmask = rp_pci_ctlmask;
/* Wake up the device. */
stcmd = pci_read_config(dev, PCIR_COMMAND, 4);
if ((stcmd & PCIM_CMD_PORTEN) == 0) {
stcmd |= (PCIM_CMD_PORTEN);
pci_write_config(dev, PCIR_COMMAND, 4, stcmd);
}
/* The IO ports of AIOPs for a PCI controller are continuous. */
ctlp->io_num = 1;
ctlp->io_rid = kmalloc(sizeof(*(ctlp->io_rid)) * ctlp->io_num,
M_DEVBUF, M_WAITOK | M_ZERO);
ctlp->io = kmalloc(sizeof(*(ctlp->io)) * ctlp->io_num,
M_DEVBUF, M_WAITOK | M_ZERO);
ctlp->bus_ctlp = NULL;
ctlp->io_rid[0] = 0x10;
ctlp->io[0] = bus_alloc_resource(dev, SYS_RES_IOPORT, &ctlp->io_rid[0], 0, ~0, 1, RF_ACTIVE);
if(ctlp->io[0] == NULL) {
device_printf(dev, "ioaddr mapping failed for RocketPort(PCI).\n");
retval = ENXIO;
goto nogo;
}
num_aiops = sPCIInitController(ctlp,
MAX_AIOPS_PER_BOARD, 0,
FREQ_DIS, 0, (pci_get_devid(dev) >> 16) & 0xffff);
num_ports = 0;
for(aiop=0; aiop < num_aiops; aiop++) {
sResetAiopByNum(ctlp, aiop);
num_ports += sGetAiopNumChan(ctlp, aiop);
}
retval = rp_attachcommon(ctlp, num_aiops, num_ports);
if (retval != 0)
goto nogo;
return (0);
nogo:
rp_pcireleaseresource(ctlp);
return (retval);
}
开发者ID:mihaicarabas,项目名称:dragonfly,代码行数:61,代码来源:rp_pci.c
示例6: add_event
static int
add_event(gs_grid_storage_t * gs, const char *cName, const char *msg)
{
int rc = -1;
gs_error_t **gserr = NULL;
gs_error_t *locerr = NULL;
struct gs_container_location_s *location = NULL;
container_id_t cid;
struct metacnx_ctx_s cnx;
gchar *hexid = NULL;
gchar * meta2_url = NULL;
GError *gerr = NULL;
metacnx_clear(&cnx);
if (!gs || !cName || !msg) {
PRINT_ERROR("Invalid parameter (%p %p %p)\n", gs, cName, msg);
return rc;
}
location = gs_locate_container_by_name(gs, cName, &locerr);
if (!location) {
PRINT_ERROR("cannot find %s\n", cName);
goto exit_label;
}
if (!location->m0_url || !location->m1_url || !location->m2_url || !location->m2_url[0]) {
PRINT_ERROR("cannot find %s\n", cName);
goto exit_label;
}
PRINT_DEBUG("%s found\n", cName);
hexid = location->container_hexid;
meta2_url = location->m2_url[0];
if (!container_id_hex2bin(hexid, strlen(hexid), &cid, &gerr)) {
GSERRORCAUSE(gserr, gerr, "Invalid container id");
goto exit_label;
}
if (!metacnx_init_with_url(&cnx, meta2_url, &gerr)) {
GSERRORCAUSE(gserr, gerr, "Invalid META2 address");
goto exit_label;
}
container_event_t event;
bzero(&event, sizeof(event));
event.timestamp = time(0);
g_strlcpy(event.type, "test", sizeof(event.type));
g_strlcpy(event.ref, "test", sizeof(event.type));
event.message = metautils_gba_from_string(msg);
PRINT_DEBUG("Adding event [%s]", msg);
rc = meta2_remote_add_container_event(&cnx, cid, &event, &gerr);
g_byte_array_free(event.message, TRUE);
event.message = NULL;
metacnx_close(&cnx);
metacnx_clear(&cnx);
if (!rc) {
PRINT_ERROR("Failed to add event : %s\n", gerror_get_message(gerr));
g_clear_error(&gerr);
}
exit_label:
return rc;
}
开发者ID:amogrid,项目名称:redcurrant,代码行数:65,代码来源:gs_add_event.c
示例7: openssh_RSA_verify
static int
openssh_RSA_verify(int type, u_char *hash, size_t hashlen,
u_char *sigbuf, size_t siglen, RSA *rsa)
{
size_t ret, rsasize = 0, oidlen = 0, hlen = 0;
int len, oidmatch, hashmatch;
const u_char *oid = NULL;
u_char *decrypted = NULL;
ret = SSH_ERR_INTERNAL_ERROR;
switch (type) {
case NID_sha1:
oid = id_sha1;
oidlen = sizeof(id_sha1);
hlen = 20;
break;
case NID_md5:
oid = id_md5;
oidlen = sizeof(id_md5);
hlen = 16;
break;
default:
goto done;
}
if (hashlen != hlen) {
ret = SSH_ERR_INVALID_ARGUMENT;
goto done;
}
rsasize = RSA_size(rsa);
if (rsasize <= 0 || rsasize > SSHBUF_MAX_BIGNUM ||
siglen == 0 || siglen > rsasize) {
ret = SSH_ERR_INVALID_ARGUMENT;
goto done;
}
if ((decrypted = malloc(rsasize)) == NULL) {
ret = SSH_ERR_ALLOC_FAIL;
goto done;
}
if ((len = RSA_public_decrypt(siglen, sigbuf, decrypted, rsa,
RSA_PKCS1_PADDING)) < 0) {
ret = SSH_ERR_LIBCRYPTO_ERROR;
goto done;
}
if (len < 0 || (size_t)len != hlen + oidlen) {
ret = SSH_ERR_INVALID_FORMAT;
goto done;
}
oidmatch = timingsafe_bcmp(decrypted, oid, oidlen) == 0;
hashmatch = timingsafe_bcmp(decrypted + oidlen, hash, hlen) == 0;
if (!oidmatch || !hashmatch) {
ret = SSH_ERR_SIGNATURE_INVALID;
goto done;
}
ret = 0;
done:
if (decrypted) {
bzero(decrypted, rsasize);
free(decrypted);
}
return ret;
}
开发者ID:hshoexer,项目名称:libopenssh,代码行数:61,代码来源:ssh-rsa.c
示例8: main
int main( int argc, char* argv[] ) {
setbuf(stdout, NULL);
INFO("%s v1.0\n", argv[0]);
config_t cfg;
global_data_t state;
struct mosquitto *mosq = NULL;
config_init(&cfg);
loadDefaults(&cfg);
loadSerialDefaults(&cfg);
if(parseArgs(argc, argv, &cfg)) {
exit(1);
}
if(parseSerialArgs(argc, argv, &cfg)) {
exit(1);
}
//config_write(&cfg, stderr);
port_t serial;
loadSerial(&cfg, &serial);
if(serial.name == NULL) {
ERR("Could not load serial configuration\n");
exit(2);
}
if(!strlen(serial.name)) {
ERR("You must specify the serial port\n");
exit(2);
}
DBG("Setting up serial port...");
state.arduino_fd = setupSerial(serial.name, serial.speed);
if(state.arduino_fd < 0) {
ERR("Failed to setup serial port %s @ %d\n", serial.name, serial.speed);
exit(2);
}
INFO("listening for event on %s\n", serial.name);
mosquitto_lib_init();
mqttserver_t mqtt;
loadMQTT(&cfg, &mqtt);
char hostname[BUF_MAX];
gethostname(hostname, BUF_MAX);
asprintf(&state.client_id, "%s.%s", hostname, (char *) strlaststr(serial.name, "/"));
mosq = mosquitto_new(state.client_id, true, &state.arduino_fd); //use port name as client id
if(!mosq) {
ERR("Couldn't create a new mosquitto client instance\n");
exit(3);
}
//TODO setup callbacks
mosquitto_log_callback_set(mosq, log_callback);
mosquitto_disconnect_callback_set(mosq, disconnect_callback);
mosquitto_connect_callback_set(mosq, connect_callback);
mosquitto_message_callback_set(mosq, message_callback);
INFO("Connecting to %s:%d ... ", mqtt.servername, mqtt.port);
if(mosquitto_connect(mosq, mqtt.servername, mqtt.port, mqtt.keepalive)){
ERR("\nUnable to connect to %s:%d.\n", mqtt.servername, mqtt.port);
exit(3);
}
INFO("done\n");
int mosq_fd = mosquitto_socket(mosq);
fd_set active_fd_set, read_fd_set;
/* Initialize the set of active sockets. */
FD_ZERO (&active_fd_set);
FD_SET (state.arduino_fd, &active_fd_set);
FD_SET (mosq_fd, &active_fd_set);
char buf[BUF_MAX];
bzero(buf,BUF_MAX);
int retries = 0;
//TODO setup syscall to stop process
while(1) {
/* Block until input arrives on one or more active sockets. */
read_fd_set = active_fd_set;
if (select (FD_SETSIZE, &read_fd_set, NULL, NULL, NULL) < 0) {
ERR("Error in select\n");
sleep(BACKOFF);
int r = mosquitto_reconnect(mosq);
retries++;
if(r != MOSQ_ERR_SUCCESS) {
ERR("Could not reconnect to broker: %s\n", strerror(r));
if(retries > MAX_RETRIES) {
/* Cleanup */
mosquitto_destroy(mosq);
mosquitto_lib_cleanup();
exit (EXIT_FAILURE);
}
} else {
retries = 0;
continue;
//.........这里部分代码省略.........
开发者ID:dgomes,项目名称:MELGA,代码行数:101,代码来源:serial.c
示例9: simpleaudio_tone
void
simpleaudio_tone(simpleaudio *sa_out, float tone_freq, size_t nsamples_dur)
{
unsigned int framesize = simpleaudio_get_framesize(sa_out);
void *buf = malloc(nsamples_dur * framesize);
assert(buf);
if ( tone_freq != 0 ) {
float wave_nsamples = simpleaudio_get_rate(sa_out) / tone_freq;
size_t i;
#define TURNS_TO_RADIANS(t) ( M_PI*2.0 * (t) )
#define SINE_PHASE_TURNS ( (float)i/wave_nsamples + sa_tone_cphase )
#define SINE_PHASE_RADIANS TURNS_TO_RADIANS(SINE_PHASE_TURNS)
switch ( simpleaudio_get_format(sa_out) ) {
case SA_SAMPLE_FORMAT_FLOAT:
{
float *float_buf = buf;
if ( sin_table_float ) {
for ( i=0; i<nsamples_dur; i++ )
float_buf[i] = sin_lu_float(SINE_PHASE_TURNS);
} else {
for ( i=0; i<nsamples_dur; i++ )
float_buf[i] = tone_mag * sinf(SINE_PHASE_RADIANS);
}
}
break;
case SA_SAMPLE_FORMAT_S16:
{
short *short_buf = buf;
if ( sin_table_short ) {
for ( i=0; i<nsamples_dur; i++ )
short_buf[i] = sin_lu_short(SINE_PHASE_TURNS);
} else {
unsigned short mag_s = 32767.0 * tone_mag + 0.5f;
if ( tone_mag > 1.0f ) // clamp to 1.0 to avoid overflow
mag_s = 32767;
if ( mag_s < 1 ) // "short epsilon"
mag_s = 1;
for ( i=0; i<nsamples_dur; i++ )
short_buf[i] = lroundf( mag_s * sinf(SINE_PHASE_RADIANS) );
}
break;
}
default:
assert(0);
break;
}
sa_tone_cphase
= fmodf(sa_tone_cphase + (float)nsamples_dur/wave_nsamples, 1.0);
} else {
bzero(buf, nsamples_dur * framesize);
sa_tone_cphase = 0.0;
}
assert ( simpleaudio_write(sa_out, buf, nsamples_dur) > 0 );
free(buf);
}
开发者ID:TagPro-PreciousRoy,项目名称:minimodem,代码行数:70,代码来源:simple-tone-generator.c
示例10: main
int main(int argc, char *argv[]) // Entrada: IP_Remota, Puerto_Remoto, Puerto_Local, Nick //
{
if(argc != 5)
{
// Se muetsra el uso correcto en caso de invocación errónea //
printf("\n¡oh oh!\nEl uso exacto del programa es el correcto:\n\t%s IP_Remota Puerto_Remoto Puerto_Local Nickname\n\n", argv[0]);
}
// Nombramiento de los parámetros recibidos //
char* programa = argv[0];
char* ip_remota = argv[1];
int puerto_remoto = atoi(argv[2]);
int puerto_local = atoi(argv[3]);
char* nick = argv[4];
printf("\n\t¡Hola %s!\n\tBienvenido a Messenger\n\n", nick);
// BIFURCACIÓN de procesos mediante el uso de fork() //
pid_t childpid; // process_ID del proceso hijo //
childpid = fork(); // Llamada a fork() //
if (childpid >= 0) // si el process_ID del hijo es >= 0, el fork fue exitoso //
{
if (childpid == 0) // fork() retorna 0 al process_ID del hijo //
{
// SERVIDOR //
int fd, fd2; // nombre que describe los sockets //
int sin_size; // Variable para el tamanno de conexiones //
char buf[1024]; // bufer para las cadenas de texto recibidas //
struct sockaddr_in server; // dirección IP del servidor //
struct sockaddr_in client; // dirección IP del cliente //
if ((fd=socket(AF_INET, SOCK_STREAM, 0)) == -1 ) // CREACION DEL SOCKET //
{
printf("error en socket()\n"); // ERROR en la creacion del socket //
exit(-1);
}
server.sin_family = AF_INET; // Asignacion de la familia del socket //
server.sin_port = htons(puerto_local); // Asignacion del Puerto_Local //
server.sin_addr.s_addr = INADDR_ANY; // Dirección IP local de manera automatica //
bzero(&(server.sin_zero),8); // Se colocan ceros en el resto de la estructura //
if(bind(fd,(struct sockaddr*)&server, sizeof(struct sockaddr))==-1) // Intento de hacer bind con los puertos ingresados //
{
printf("ERROR Puerto ocupado\n"); // ERROR en caso de que no se pueda completar el bind //
exit(-1);
}
if(listen(fd,1) == -1) // llamada al proceso de escucha, 2do arg es num de conexiones permitidas //
{
printf("error en listen()\n"); // ERROR en caso que falle el proceso de listen //
exit(-1);
}
sin_size = sizeof(struct sockaddr_in); // Se captura el tamanno para realizar conexiones //
if ((fd2 = accept(fd,(struct sockaddr *)&client, &sin_size))==-1) // Valida que la conexion sea aceptada //
{
printf("error en accept()\n"); // ERROR en caso que no se pueda aceptar la conexion entrante //
exit(-1);
}
// Se muestra ip remota //
printf("\tUn amigo se ha conectado desde: %s\n\tPara chatear solo teclea y presiona Enter\n\n", (char*)inet_ntoa(client.sin_addr));
while (strcmp(buf,"Adios") != 0) // revisa que el mensaje entrante no sea "Adios" //
{
if ((recv(fd2,buf,1024,0)) > 0) // Recibe el mensaje y valida error //
{
printf("%s dice: %s\n",nick, buf); // muestra el mensaje recibido //
}
}
close(fd2); // Se finaliza la conexion //
close(fd); // Se finaliza el socket //
printf("\tTu [email protected] terminó la conversación,\n\tVuelve pronto...!\n\n"); // AVISO si el proceso remoto finaliza la charla //
exit(-1); // Sale del Programa //
} // FIN del proceso padre //
else //fork() retorna process_ID del hijo al padre//
{
// CLIENTE //
int fd; // nombre que describe los sockets //
struct hostent *he; // estructura para informacion del proceso remoto //
struct sockaddr_in server; // dirección IP del servidor //
if ((he=gethostbyname(ip_remota))==NULL) // se comprueba la direccion IP_Remota //
{
printf("gethostbyname() error\n"); // ERROR en caso de no poder verificar la IP_Remota //
exit(-1);
//.........这里部分代码省略.........
开发者ID:Yesenia1,项目名称:Tarea_programada1,代码行数:101,代码来源:Progra_C.c
示例11: read_ts_err_stats
void
read_ts_err_stats(struct module *mod)
{
int fd = -1;
int pos;
char buf[LINE_4096];
struct sockaddr_un un;
struct stats_ts_err st_ts;
if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
goto done;
}
bzero(&st_ts, sizeof(st_ts));
bzero(&un, sizeof(un));
un.sun_family = AF_UNIX;
strcpy(un.sun_path, sock_path);
if (connect(fd, (struct sockaddr *)&un, sizeof(un)) < 0) {
goto done;
}
int i, len;
int record_len = sizeof(RECORDS_NAME) / sizeof(RECORDS_NAME[0]);
const char *info;
for ( i = 0; i < record_len; ++i) {
info = RECORDS_NAME[i];
long int info_len = strlen(info);
short int command = TS_RECORD_GET;
char write_buf[LINE_1024];
*((short int *)&write_buf[0]) = command;
*((long int *)&write_buf[2]) = info_len;
strcpy(write_buf + 6, info);
len = 2 + 4 + strlen(info);
if (write(fd, write_buf, len) != len) {
close(fd);
return;
}
short int ret_status = 0;
short int ret_type = 0;
long ret_val = 0;
int read_len = read(fd, buf, LINE_1024);
if (read_len != -1) {
ret_status = *((short int *)&buf[0]);
ret_type = *((short int *)&buf[6]);
} else {
close(fd);
return;
}
if (0 == ret_status) {
if (ret_type < 2) {
ret_val= *((long int *)&buf[8]);
} else if (2 == ret_type) {
float ret_val_float = *((float *)&buf[8]);
ret_val_float *= 100;
ret_val = (unsigned long long)ret_val_float;
} else {
goto done;
}
}
((unsigned long long *)&st_ts)[i] = ret_val;
}
done:
if (-1 != fd) {
close(fd);
}
pos = sprintf(buf, "%lld,%lld,%lld,%lld,%lld,%lld,%lld,%lld",
st_ts.miss_host,
st_ts.aborts,
st_ts.pre_accept_hangups,
st_ts.empty_hangups,
st_ts.early_hangups,
st_ts.con_fail,
st_ts.other,
st_ts.hangup
);
buf[pos] = '\0';
set_mod_record(mod, buf);
}
开发者ID:0xmalloc,项目名称:tsar,代码行数:80,代码来源:mod_ts_err.c
示例12: snc_isa_probe
static int
snc_isa_probe(device_t dev)
{
struct snc_softc *sc = device_get_softc(dev);
int type;
int error = 0;
bzero(sc, sizeof(struct snc_softc));
/* Check isapnp ids */
error = ISA_PNP_PROBE(device_get_parent(dev), dev, snc_ids);
/* If the card had a PnP ID that didn't match any we know about */
if (error == ENXIO) {
return(error);
}
switch (error) {
case 0: /* Matched PnP */
type = SNEC_TYPE_PNP;
break;
case ENOENT: /* Legacy ISA */
type = SNEC_TYPE_LEGACY;
break;
default: /* If we had some other problem. */
return(error);
}
if (type == SNEC_TYPE_PNP && isa_get_portsize(dev) == 0) {
int port;
int rid = 0;
struct resource *res = NULL;
for (port = 0x0888; port <= 0x3888; port += 0x1000) {
bus_set_resource(dev, SYS_RES_IOPORT, rid,
port, SNEC_NREGS);
res = bus_alloc_resource(dev, SYS_RES_IOPORT, &rid,
0ul, ~0ul, SNEC_NREGS,
0 /* !RF_ACTIVE */);
if (res) break;
}
printf("snc_isa_probe: broken PnP resource, ");
if (res) {
printf("use port 0x%x\n", port);
bus_release_resource(dev, SYS_RES_IOPORT, rid, res);
snc_isapnp_reconfig(dev);
} else {
printf("and can't find port\n");
}
}
error = snc_alloc_port(dev, 0);
error = max(error, snc_alloc_memory(dev, 0));
error = max(error, snc_alloc_irq(dev, 0, 0));
if (!error && !snc_probe(dev, type))
error = ENOENT;
snc_release_resources(dev);
return (error);
}
开发者ID:dcui,项目名称:FreeBSD-9.3_kernel,代码行数:64,代码来源:if_snc_cbus.c
示例13: main
int
main(int argc, char *argv[])
{
int i, cc, fd;
uint rootino, inum, off;
struct dirent de;
char buf[BSIZE];
struct dinode din;
static_assert(sizeof(int) == 4, "Integers must be 4 bytes!");
if(argc < 2){
fprintf(stderr, "Usage: mkfs fs.img files...\n");
exit(1);
}
assert((BSIZE % sizeof(struct dinode)) == 0);
assert((BSIZE % sizeof(struct dirent)) == 0);
fsfd = open(argv[1], O_RDWR|O_CREAT|O_TRUNC, 0666);
if(fsfd < 0){
perror(argv[1]);
exit(1);
}
// 1 fs block = 1 disk sector
nmeta = 2 + nlog + ninodeblocks + nbitmap;
nblocks = FSSIZE - nmeta;
sb.size = xint(FSSIZE);
sb.nblocks = xint(nblocks);
sb.ninodes = xint(NINODES);
sb.nlog = xint(nlog);
sb.logstart = xint(2);
sb.inodestart = xint(2+nlog);
sb.bmapstart = xint(2+nlog+ninodeblocks);
printf("nmeta %d (boot, super, log blocks %u inode blocks %u, bitmap blocks %u) blocks %d total %d\n",
nmeta, nlog, ninodeblocks, nbitmap, nblocks, FSSIZE);
freeblock = nmeta; // the first free block that we can allocate
for(i = 0; i < FSSIZE; i++)
wsect(i, zeroes);
memset(buf, 0, sizeof(buf));
memmove(buf, &sb, sizeof(sb));
wsect(1, buf);
rootino = ialloc(T_DIR);
assert(rootino == ROOTINO);
bzero(&de, sizeof(de));
de.inum = xshort(rootino);
strcpy(de.name, ".");
iappend(rootino, &de, sizeof(de));
bzero(&de, sizeof(de));
de.inum = xshort(rootino);
strcpy(de.name, "..");
iappend(rootino, &de, sizeof(de));
for(i = 2; i < argc; i++){
assert(index(argv[i], '/') == 0);
if((fd = open(argv[i], 0)) < 0){
perror(argv[i]);
exit(1);
}
// Skip leading _ in name when writing to file system.
// The binaries are named _rm, _cat, etc. to keep the
// build operating system from trying to execute them
// in place of system binaries like rm and cat.
if(argv[i][0] == '_')
++argv[i];
inum = ialloc(T_FILE);
bzero(&de, sizeof(de));
de.inum = xshort(inum);
strncpy(de.name, argv[i], DIRSIZ);
iappend(rootino, &de, sizeof(de));
while((cc = read(fd, buf, sizeof(buf))) > 0)
iappend(inum, buf, cc);
close(fd);
}
// fix size of root inode dir
rinode(rootino, &din);
off = xint(din.size);
off = ((off/BSIZE) + 1) * BSIZE;
din.size = xint(off);
winode(rootino, &din);
balloc(freeblock);
//.........这里部分代码省略.........
开发者ID:bdobyns,项目名称:xv6-public,代码行数:101,代码来源:mkfs.c
示例14: ctf_fdopen
/*
* Open the specified file descriptor and return a pointer to a CTF container.
* The file can be either an ELF file or raw CTF file. The caller is
* responsible for closing the file descriptor when it is no longer needed.
*/
ctf_file_t *
ctf_fdopen(int fd, int *errp)
{
ctf_sect_t ctfsect, symsect, strsect;
ctf_file_t *fp = NULL;
size_t shstrndx, shnum;
struct stat64 st;
ssize_t nbytes;
union {
ctf_preamble_t ctf;
Elf32_Ehdr e32;
GElf_Ehdr e64;
} hdr;
bzero(&ctfsect, sizeof (ctf_sect_t));
bzero(&symsect, sizeof (ctf_sect_t));
bzero(&strsect, sizeof (ctf_sect_t));
bzero(&hdr.ctf, sizeof (hdr));
if (fstat64(fd, &st) == -1)
return (ctf_set_open_errno(errp, errno));
if ((nbytes = pread64(fd, &hdr.ctf, sizeof (hdr), 0)) <= 0)
return (ctf_set_open_errno(errp, nbytes < 0? errno : ECTF_FMT));
/*
* If we have read enough bytes to form a CTF header and the magic
* string matches, attempt to interpret the file as raw CTF.
*/
if (nbytes >= (ssize_t) sizeof (ctf_preamble_t) &&
hdr.ctf.ctp_magic == CTF_MAGIC) {
if (hdr.ctf.ctp_version > CTF_VERSION)
return (ctf_set_open_errno(errp, ECTF_CTFVERS));
ctfsect.cts_data = mmap64(NULL, st.st_size, PROT_READ,
MAP_PRIVATE, fd, 0);
if (ctfsect.cts_data == MAP_FAILED)
return (ctf_set_open_errno(errp, errno));
ctfsect.cts_name = _CTF_SECTION;
ctfsect.cts_type = SHT_PROGBITS;
ctfsect.cts_flags = SHF_ALLOC;
ctfsect.cts_size = (size_t)st.st_size;
ctfsect.cts_entsize = 1;
ctfsect.cts_offset = 0;
if ((fp = ctf_bufopen(&ctfsect, NULL, NULL, errp)) == NULL)
ctf_sect_munmap(&ctfsect);
return (fp);
}
/*
* If we have read enough bytes to form an ELF header and the magic
* string matches, attempt to interpret the file as an ELF file. We
* do our own largefile ELF processing, and convert everything to
* GElf structures so that clients can operate on any data model.
*/
if (nbytes >= (ssize_t) sizeof (Elf32_Ehdr) &&
bcmp(&hdr.e32.e_ident[EI_MAG0], ELFMAG, SELFMAG) == 0) {
#if BYTE_ORDER == _BIG_ENDIAN
uchar_t order = ELFDATA2MSB;
#else
uchar_t order = ELFDATA2LSB;
#endif
GElf_Shdr *sp;
void *strs_map;
size_t strs_mapsz, i;
char *strs;
if (hdr.e32.e_ident[EI_DATA] != order)
return (ctf_set_open_errno(errp, ECTF_ENDIAN));
if (hdr.e32.e_version != EV_CURRENT)
return (ctf_set_open_errno(errp, ECTF_ELFVERS));
if (hdr.e32.e_ident[EI_CLASS] == ELFCLASS64) {
if (nbytes < (ssize_t) sizeof (GElf_Ehdr))
return (ctf_set_open_errno(errp, ECTF_FMT));
} else {
Elf32_Ehdr e32 = hdr.e32;
ehdr_to_gelf(&e32, &hdr.e64);
}
shnum = hdr.e64.e_shnum;
shstrndx = hdr.e64.e_shstrndx;
/* Extended ELF sections */
if ((shstrndx == SHN_XINDEX) || (shnum == 0)) {
if (hdr.e32.e_ident[EI_CLASS] == ELFCLASS32) {
Elf32_Shdr x32;
//.........这里部分代码省略.........
开发者ID:Alkzndr,项目名称:freebsd,代码行数:101,代码来源:ctf_lib.c
示例15: udp_ipsec_input
/*
* Potentially decap ESP in UDP frame. Check for an ESP header.
* If present, strip the UDP header and push the result through IPSec.
*
* Returns error if mbuf consumed and/or processed, otherwise 0.
*/
int
udp_ipsec_input(struct mbuf *m, int off, int af)
{
union sockaddr_union dst;
struct secasvar *sav;
struct udphdr *udp;
struct ip *ip;
uint32_t spi;
int hlen;
/*
* Just return if packet doesn't have enough data.
* We need at least [IP header + UDP header + ESP header].
* NAT-Keepalive packet has only one byte of payload, so it
* by default will not be processed.
*/
if (m->m_pkthdr.len < off + sizeof(struct esp))
return (0);
m_copydata(m, off, sizeof(uint32_t), (caddr_t)&spi);
if (spi == 0) /* Non-ESP marker. */
return (0);
/*
* Find SA and check that it is configured for UDP
* encapsulation.
*/
bzero(&dst, sizeof(dst));
dst.sa.sa_family = af;
switch (af) {
#ifdef INET
case AF_INET:
dst.sin.sin_len = sizeof(struct sockaddr_in);
ip = mtod(m, struct ip *);
ip->ip_p = IPPROTO_ESP;
off = offsetof(struct ip, ip_p);
hlen = ip->ip_hl << 2;
dst.sin.sin_addr = ip->ip_dst;
break;
#endif
#ifdef INET6
case AF_INET6:
/* Not yet */
/* FALLTHROUGH */
#endif
default:
ESPSTAT_INC(esps_nopf);
m_freem(m);
return (EPFNOSUPPORT);
}
sav = key_allocsa(&dst, IPPROTO_ESP, spi);
if (sav == NULL) {
ESPSTAT_INC(esps_notdb);
m_freem(m);
return (ENOENT);
}
udp = mtodo(m, hlen);
if (sav->natt == NULL ||
sav->natt->sport != udp->uh_sport ||
sav->natt->dport != udp->uh_dport) {
/* XXXAE: should we check source address? */
ESPSTAT_INC(esps_notdb);
key_freesav(&sav);
m_freem(m);
return (ENOENT);
}
/*
* Remove the UDP header
* Before:
* <--- off --->
* +----+------+-----+
* | IP | UDP | ESP |
* +----+------+-----+
* <-skip->
* After:
* +----+-----+
* | IP | ESP |
* +----+-----+
* <-skip->
*/
m_striphdr(m, hlen, sizeof(*udp));
/*
* We cannot yet update the cksums so clear any h/w cksum flags
* as they are no longer valid.
*/
if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID)
m->m_pkthdr.csum_flags &= ~(CSUM_DATA_VALID | CSUM_PSEUDO_HDR);
/*
* We can update ip_len and ip_sum here, but ipsec4_input_cb()
* will do this anyway, so don't touch them here.
*/
ESPSTAT_INC(esps_input);
(*sav->tdb_xform->xf_input)(m, sav, hlen, off);
//.........这里部分代码省略.........
开发者ID:2trill2spill,项目名称:freebsd,代码行数:101,代码来源:udpencap.c
示例16: main
/* main */
int main(int argc, char *argv[])
{
struct arguments arguments;
bzero (&arguments, sizeof(struct arguments));
if (argp_parse (&argp, argc, argv, 0, 0, &arguments) == ARGP_KEY_ERROR){
fprintf(stderr,
"[rastro_generate] at %s,"
"error during the parsing of parameters\n",
__func__);
return 1;
}
FILE *header = fopen (arguments.header_file, "w");
if (!header){
fprintf(stderr,
"[rastro_generate] at %s,"
"could not open file %s for writing\n",
__func__, arguments.header_file);
return 1;
}
FILE *implem = fopen (arguments.implementation_file, "w");
if (!implem){
fprintf(stderr,
"[rastro_generate] at %s,"
"could not open file %s for writing\n",
__func__, arguments.implementation_file);
fclose (header);
return 1;
}
if (arguments.from_file){
FILE *file = fopen (arguments.from_file, "r");
if (!file){
fprintf(stderr,
"[rastro_generate] at %s,"
"could not open file %s for reading\n",
__func__, arguments.from_file);
fclose (header);
fclose (implem);
return 1;
}
while (feof(file)==0){
char read_str[100];
if (fscanf (file, "%s", read_str) != 1) break;
if (feof(file)) break;
arguments.input[arguments.input_size] = strdup (read_str);
arguments.input_size++;
}
fclose (file);
}
rst_generate (arguments.input,
arguments.input_size,
header,
implem,
arguments.header_file);
fclose (header);
fclose (implem);
return 0;
}
开发者ID:schnorr,项目名称:librastro,代码行数:64,代码来源:rst_generate.c
示例17: gmsvproto_sv_callback
void gmsvproto_sv_callback(int sock, short event, void* arg)
{
struct event* write_ev;
int size;
struct sock_ev* ev = (struct sock_ev*)arg;
//初始化通信NetPacket以及内部buffer
//这部分内容在如下函数中释放
//函数gmsvproto_sv.c:on_write()最后部分
ev->packet = (struct NetPacket*)malloc(sizeof(struct NetPacket));
if (ev->packet == NULL)
{
char string[256];
sprintf(string, "[ERROR]gmsvproto_sv.c:gmsvproto_sv_callback() malloc ev->packet failed!\n");
LogWrite(LT_SYSTEM, string);
printf(string);
}
ev->packet->m_buffer = (unsigned char*)malloc(DEFAULT_SIZE);
if (ev->packet->m_buffer == NULL)
{
char string[256];
sprintf(string, "[ERROR]gmsvproto_sv.c:gmsvproto_sv_callback() malloc ev->packet->m_buffer failed!\n");
LogWrite(LT_SYSTEM, string);
printf(string);
}
bzero(ev->packet->m_buffer, DEFAULT_SIZE);
ev->packet->opcode = 0;
ev->packet->m_readPos = 0;
ev->packet->m_writePos = 0;
ev->packet->m_buffersize = DEFAULT_SIZE;
//接受服务器数据
size = recv(sock, ev->packet->m_buffer, DEFAULT_SIZE, 0);
if (size == -1)
{
if (errno == 104)
{
//暂时忽略104 Connection reset by peer
//因为目前客户端断开连接会收到这个消息
//不处理会导致服务器崩溃
return;
}
}
if (size == 0)
{
//客户端断开连接
//这里需要处理断开连接的处理
closePlayerSocketBySockid(sock);
}
printf("sock = %d, receive data:%s, size:%d\n",sock, ev->packet->m_buffer, size);
//获取数据包的长度
memcpy(&(ev->packet->m_writePos), ev->packet->m_buffer + sizeof(uint16_t), sizeof(uint16_t));
if (size == 0) {
release_sock_event(ev);
close(sock);
printf("sock = %d, closed!\n", sock);
return;
}
event_set(ev->write_ev, sock, EV_WRITE, on_write, ev);
event_base_set(base, ev->write_ev);
event_add(ev->write_ev, NULL);
}
开发者ID:hsw625728,项目名称:Life,代码行数:64,代码来源:gmsvproto_sv.c
|
请发表评论